最長不重複的子串長度

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

思路一,我自己的思路採用的是hashmap來保存每次出現的字符,當出現重複字符的時候,就記錄這段的最長,然後重新開始。但是這樣很浪費時間,重複了一些步驟。

class Solution {
    public int lengthOfLongestSubstring(String s) {
  //採用hashmap的簡單解法
          int result = 0;
        //從第一個字符開始
        for(int i = 0; i < s.length(); i++)
        {
            Map<Character, Integer> hmap = new HashMap<>();
            int count = 0;
            //計算從第一個字符開始的不重複子串
            for(int j = i ; j < s.length(); j++)
            {
                if(!hmap.containsKey(s.charAt(j)))
                {
                    hmap.put(s.charAt(j),1);
                    count++;
                }
                else
                    break;
            }
            //保存當前最大的子串
            if(count >= result)
                result = count;
        }
        return result;
       }
      } 

思路二:開闢一個能容納所有字母ASCII碼大小的數組,用字母當下標,值當出現的位置,用一個指針來指示從不重複的位置開始。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] m = new int[256];
        Arrays.fill(m, -1);
        int res = 0, left = -1;
        for (int i = 0; i < s.length(); ++i) {
            //當出現重複的時候,從這個重複的位置重新開始,實際上是從下一個位置開始的
            left = Math.max(left, m[s.charAt(i)]);
            m[s.charAt(i)] = i;//字母當下標,位置當值
            //求每次不重複的子串
            res = Math.max(res, i - left);
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章