leetcode之 Longest Substring Without Repeating Characters

problem:
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 ,如果已经找到abcabcb的最优长度max,那么abcabcbb的长度是多少呢?

public int lengthOfLongestSubstring1(String s) {
        if(s==null || s.equals(""))
            return 0;  
        char[] sArray=s.toCharArray();
        ArrayList<Character> sum=new ArrayList<Character>();
        int max=1;
        sum.add(sArray[0]);
        for(int i=1;i<sArray.length;i++){
            if(sum.contains(sArray[i]) ){
                int index=sum.indexOf(sArray[i]);
                sum.removeAll(sum.subList(0,index+1));
                sum.add(sArray[i]);
            }else{
                sum.add(sArray[i]);
            }
            max=Math.max(max,sum.size());
        }
        return max;
    }

先把求出来的子串最大的长度放入max,然后遍历下一个字符,看它是否存在在前面的字符串,如果存在,那么一个不包含重复元素的新的字串,必定是要把重复元素以及它前面的元素清空,然后再把它的长度和max比较,就可以得出最新的长度。

但是,我这种解法,虽然思想上是对的,但是在实现上确实很粗糙,实现最精致的是leetcode上速度最快的那种。

public int lengthOfLongestSubstring(String s) {

        int i=0;
        int j=0;
        int max=0;
        HashSet<Character> set=new HashSet<Character>();
        while (j<s.length()){
            if(!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                max=Math.max(max,set.size());
            }else{
                set.remove(s.charAt(i++));
            }
        }
        return max;
    }

思想上是一致的。实现上的差距:
1.为了遍历,我把字符串转换成了字符数组。实际上,可以通过
s.charAt(i).就可以像数组一样遍历。
2.为了清空重复元素以及所有前面的元素,我是通过ArrayList中的
sum.removeAll(sum.subList(0,index+1)); 移除字串的形式。
实际上,通过两个指针可以解决这个问题。
指针 j 用来表示遍历到哪一个元素。
指针 i 用来表示重复元素的位置。
利用set.remove(s.charAt(i++)) 一直运行到移除重复元素的位置,于是set中就只含有后面字串的元素。

猜你喜欢

转载自blog.csdn.net/mooneal/article/details/76687048