3.Longest Substring Without Repeating Characters

最长子串

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.

代码

 public int lengthOfLongestSubstring(String s) {
        int maxLength = 0;
        String temp = "";
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(!temp.contains(c + "")){
                temp = Strings.concat(temp,c);
                if(temp.length() > maxLength) {
                    maxLength = temp.length();
                }
            }else {
                int k = temp.indexOf(c);
                temp = temp.substring(k+1) + c;
            }
        }
        return maxLength;
    }

分析

一个变量记录当前最大长度,一个变量记录当前子串
没找到重复的就加到当前子串上,然后跟当前记录的最大长度进行比较取最大值,
找到重复的时候把子串重设为重复的那个字符开始取值!!

你可能感兴趣的:(3.Longest Substring Without Repeating Characters)