leetcode做题总结,题目Longest Substring Without Repeating Characters

来源:互联网 发布:重生网络女主播txt 编辑:程序博客网 时间:2024/05/21 18:33

题目链接Longest Substring Without Repeating Characters

这道题使用了窗口的概念,在有关子字符串的题目中可以考虑,即使用前后两个指针控制一个窗口,窗口里包含的便是这个没有重复字符的子字符串。

public class Solution {    public int lengthOfLongestSubstring(String s) {        if(s.length()==0)            return 0;        HashSet<Character> set = new HashSet<Character>();        int max=0;        int first=0;        int last=0;        while(first<s.length()){            if(set.contains(s.charAt(first))){                if(max<first-last)                    max=first-last;                while(s.charAt(first)!=s.charAt(last)){                    set.remove(s.charAt(last));                    last++;                }                if(last!=first)                    last++;                first++;            }else{                set.add(s.charAt(first));                first++;            }        }        if(max<first-last)            max=first-last;        return max;    }}

Update 2015/08/31: 下面的思路和上面的一样。只是用boolean数组代替HashSet来储存子串不同的字符,当下一个字符和窗口里的有重复是,缩短窗口

public class Solution {    public int lengthOfLongestSubstring(String s) {        if(s==null)            return 0;boolean[] flag = new boolean[256]; int result = 0;int start = 0;char[] arr = s.toCharArray(); for (int i = 0; i < arr.length; i++) {char current = arr[i];if (flag[current]) {result = Math.max(result, i - start);// the loop update the new start point// and reset flag array// for example, abccab, when it comes to 2nd c,// it update start from 0 to 3, reset flag for a,bfor (int k = start; k < i; k++) {if (arr[k] == current) {start = k + 1; break;}flag[arr[k]] = false;}} else {flag[current] = true;}} result = Math.max(arr.length - start, result); return result;    }}



0 0
原创粉丝点击