IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 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.

          本題比較簡單,需要注意的是左指針右移時,需要將它掠過的元素從map中移除。實現代碼如下:
           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) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 临湘市| 象州县| 葫芦岛市| 苍梧县| 藁城市| 临沭县| 海口市| 和田市| 陵川县| 封开县| 澄城县| 呼图壁县| 阳高县| 三亚市| 江门市| 固始县| 荥阳市| 莱州市| 兴城市| 绥滨县| 阿合奇县| 黔东| 始兴县| 东乌珠穆沁旗| 马鞍山市| 冀州市| 南宁市| 富川| 禹城市| 雅安市| 博客| 镇平县| 汶川县| 莎车县| 永嘉县| 清新县| 大竹县| 弥勒县| 韩城市| 延安市| 瑞丽市|