IT技術(shù)小屋

          秋風(fēng)秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評(píng)論 :: 0 Trackbacks
          Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

          本題比較簡(jiǎn)單,需要注意的是左指針右移時(shí),需要將它掠過的元素從map中移除。實(shí)現(xiàn)代碼如下:
           1 public class Solution {
           2     public int lengthOfLongestSubstring(String s) {
           3         int length = s.length();
           4         if (length == 0) return 0;
           5         Map<Character, Integer> map = new HashMap<Character, Integer>();
           6         int ret = 0;
           7         int count = 0;
           8         int start = 0;
           9         for (int i = 0; i < length; i++) {
          10             char c = s.charAt(i);
          11             if (map.containsKey(c)) {
          12                 int newStart = map.remove(c).intValue() + 1;
          13                 for (int j = start; j < newStart; j++) {
          14                     map.remove(s.charAt(j));
          15                 }
          16                 start = newStart;
          17                 ret = ret < count ? count : ret;
          18                 count = i - start + 1;
          19             } else {
          20                 count++;
          21             }
          22             map.put(c, i);
          23         }
          24         return ret < count ? count : ret;
          25     }
          26 }
          posted on 2013-12-22 20:07 Meng Lee 閱讀(646) 評(píng)論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 甘泉县| 邹城市| 盱眙县| 明水县| 平和县| 普安县| 苏州市| 岱山县| 璧山县| 泽普县| 丰城市| 贵定县| 芒康县| 新巴尔虎左旗| 兴化市| 开阳县| 宁陕县| 兴文县| 彰化市| 瑞丽市| 汤阴县| 凤阳县| 湟中县| 贺州市| 繁峙县| 峨边| 石棉县| 建德市| 聂拉木县| 百色市| 白山市| 景洪市| 抚宁县| 阿鲁科尔沁旗| 滨海县| 武夷山市| 陆河县| 邛崃市| 鄯善县| 三原县| 博湖县|