0003_Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝做什么生意好赚钱 编辑:程序博客网 时间:2024/06/05 04:20

C++

感谢praveen_uchiha分享

class Solution {public:    int lengthOfLongestSubstring(string s) {        int currentLength = 0;        int max = 0;        int index = 0;        string shortestString;        for(int i = 0; i < s.length(); ++i)        {            index = shortestString.find(s[i]);            if(index != string::npos)            {                if(max < shortestString.length())                {                    max = shortestString.length();                }                shortestString.erase(shortestString.begin(),shortestString.begin() + index +1);            }            shortestString.push_back(s[i]);        }        if(max < shortestString.length())        {            max = shortestString.length();        }        return max;    }};

JAVA

过了好久,重新用java做这个题,发现原来学的思路全忘了。。。所以最开始用两层循环,提交后果断超时,然后想到使用hashmap保存当前子串中已经存在的字符,在便利后续字符的时候检查该字符是否已经存在,若存在则比较当前子串长度和result长度,取大值,然后将新子串定义的起点定义在该字符处,

        public int lengthOfLongestSubstring(String s) {            HashMap<Character,Integer> hmap = new HashMap<Character, Integer>();            int result = 0;            int i = 0;            int j = 0;            while(j < s.length()){                if(hmap.containsKey(s.charAt(j)) && hmap.get(s.charAt(j)) >= i){                    result = result > (j - i) ? result : (j - i);                    i = hmap.get(s.charAt(j)) + 1;                    hmap.put(s.charAt(j),j);                }                hmap.put(s.charAt(j),j);                ++j;            }            result = result > (j - i) ? result : (j - i);            return result;        }

没错,这个代码没过,在测试’dvdf’时,应该返回3,但是上述代码返回2。想了好久也没想出来,就去做运动去了。。。。运动个过程中忽然想到,当出现重复字符的时候,新的子串的起始位置应该是该字符上次出现的后一位,这样才能使子串的长度最大化,因此又有了下面的代码:

        public int lengthOfLongestSubstring(String s) {            HashMap<Character,Integer> hmap = new HashMap<Character, Integer>();            int result = 0;            int i = 0;            int j = 0;            while(j < s.length()){                if(hmap.containsKey(s.charAt(j)) && hmap.get(s.charAt(j)) >= i){                    result = result > (j - i) ? result : (j - i);                    i = hmap.get(s.charAt(j)) + 1;                    hmap.put(s.charAt(j),j);                }                hmap.put(s.charAt(j),j);                ++j;            }            result = result > (j - i) ? result : (j - i);            return result;        }

这次顺利AC了,虽然时间不是很好,只处于中游水平,但是这个之前一直学不会的方法,终于想明白了。。。。

0 0