最長子串(Leetcode-3 Longest Substring Without Repeating Characters)


Question:

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.

問題描述:

給一個字符串,找出這個字符串的無重復字符的最長子串的長度。

實例:

1,“abcabcbb”的最長子串是“abc”,長度為3。

2,“bbbbb”的最長子串是“b”,長度為1。

3,“pwwkew”的最長子串是“wke”,長度為3。

 

解題思路:

這個題的關鍵在於重復的字符!

一個子串不可能出現重復的字符,那么我們可以用兩個指針,一個指針用來遍歷字符串,兩個指針之間保持無重復字符,那么兩個指針之間的長度即最大子串的長度。當發現有重復的字符時,另一個指針指向這個字符上一次出現的位置的下一個字符,繼續遍歷,直到找到最長子串。

代碼示例:

 1 public int lengthOfLongestSubstring(String s) {
 2         if (s.length()==0) return 0;
 3         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 4         int max=0;
 5         for (int i=0, j=0; i<s.length(); ++i){
 6             if (map.containsKey(s.charAt(i))){
 7                 j = Math.max(j,map.get(s.charAt(i))+1);
 8             }
 9             map.put(s.charAt(i),i);
10             max = Math.max(max,i-j+1);
11         }
12         return max;
13     }
View Code

 

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM