1. 程式人生 > >[LeetCode]無重復字符的最長子串

[LeetCode]無重復字符的最長子串

註意 ron etc 解題思路 new wke 而不是 clas 更新

給定一個字符串,找出不含有重復字符的最長子串的長度。

示例 1:

輸入: "abcabcbb"
輸出: 3 
解釋: 無重復字符的最長子串是 "abc",其長度為 3。

示例 2:

輸入: "bbbbb"
輸出: 1
解釋: 無重復字符的最長子串是 "b",其長度為 1。

示例 3:

輸入: "pwwkew"
輸出: 3
解釋: 無重復字符的最長子串是 "wke",其長度為 3。
     請註意,答案必須是一個子串,"pwke" 是一個子序列 而不是子串。

解題思路

建立一個List或者Hashset也行,用來存儲這個子串.用一個變量(我這裏用temp)來存儲子串的長度,然後用for循環遍歷整個字符串,如果List當中有當前遍歷到的字符,則將List當中的這個字符的位置找出來,將這個位置和這個位置之前的字符去除,然後將當前遍歷的字符加入進去,

如果List的長度大於temp,將List的長度賦值給temp,如果當中沒有這個字符,則添加到List裏面去,同樣更新temp的值

值得註意:List中的remove方法要從大到小刪除,否則容易報越界異常

代碼:

class Solution {
    public int lengthOfLongestSubstring(String s) {
          if(s.length()==0)
               return 0;
            List<Character> list = new ArrayList<>();
           
int temp = 0; char it; int loc = 0; for(int i = 0;i < s.length();i++) { it = s.charAt(i); if(list.contains(it)) { loc = list.indexOf(it); for(int j = loc; j >= 0;j--) { list.remove(list.get(j)); } list.add(it);
if(list.size()>temp) { temp = list.size(); } }else { list.add(it); if(list.size()>=temp) temp = list.size(); } } return temp; } }

[LeetCode]無重復字符的最長子串