Longest Substring Without Repeating Characters

题目
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.

答案

从左到右扫描,记录当前出现过的字符,如果碰到重复字符,left = left + 1,继续往右边扫描
最后记得取Math.max(res, s.length() - start);

public class Solution {
public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0)
            return 0;
        int res = 1;
        boolean[] exist = new boolean[256];
        int start = 0;
 
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (exist[ch]) {
                res = Math.max(res, i - start);
                for (int k = start; k < i; k++) {
                    if (s.charAt(k) == ch) {
                        start = k + 1;
                        break;
                    }
                    exist[s.charAt(k)] = false;
                }
            } else
                exist[ch] = true;
        }
        res = Math.max(res, s.length() - start);
        return res;
 
    }
}

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