1. 程式人生 > >LeetCode---------Longest Substring Without Repeating Characters解法

LeetCode---------Longest Substring Without Repeating Characters解法

++ 序列 break 不重復 bst style eat java代碼 tin

題目如下:


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.


大致翻譯:


給出一個字符串,求出沒有重復字符的最長子串的長度。

例如:

給出"abcabcbb",答案是"abc"的長度為3.

給出"bbbbb",答案是"b"的長度為1.

給出"pwwkew",答案是"wke"的長度為3. 註意答案必須是一個子串,"pwke"是一個子序列但並不是子串.


本題重點在於不重復的子串,想到HashSet是不允許存儲重復的數據的,所以解法就利用HashSet來實現。

【Java代碼】

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        //不重復子串的長度
        int length = 0;
        
        //構造不重復的set表
        Set<Character> set = new HashSet<Character>();
        
        int i = 0, j = 0;
        
        for(i = 0; i < s.length(); i++){
            set.clear();//清空set表
            set.add(s.charAt(i));//加入開始字符
            for(j = i + 1; j < s.length(); j++){
                if(set.add(s.charAt(j)));//如果成功加入,證明沒有重復,程序繼續
                else break;//如果沒成功加入,則跳出
            }
            if(j - i >= length) length = j - i;//計算長度並保留最長長度
        }
        
        return length;
        
    }
}

  

如果有任何問題,歡迎跟我聯系:[email protected]

我的github地址:github.com/WXRain

LeetCode---------Longest Substring Without Repeating Characters解法