首页 > 代码库 > Leet Code Longest Substring Without Repeating Characters

Leet Code Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.



给定字符串,输出最长不重复子序列。



算法:

双指针扫描


设置两个指针,start为满足串的初始化位置,cur为当前指针位置。


首先start 为 0,cur开始逐个扫描。如果扫描的元素flag为false表示为未出现过的,则标记其为true.

同时跟新最大长度串。


如果遇到的是true,则表示为扫描过的。则循环start并逐个重新标注为未扫描过的。


循环环整个串的元素后结束程序。


输出结果。


public class Solution {
    public int lengthOfLongestSubstring(String s) {
        boolean[] flag = new boolean[500];
        java.util.Arrays.fill(flag,false);
        int max = 0;
        for(int start=0,cur=0;cur<s.length();cur++)
        {
            while(flag[s.charAt(cur)]==true)
            {
                flag[s.charAt(start)] = false;
                start++;
            }
            flag[s.charAt(cur)]=true;
            max = Math.max(max,cur-start+1);
        }
        return max;
    }
}


Leet Code Longest Substring Without Repeating Characters