leetcode#3-Longest Substring Without Repeating Characters-java

来源:互联网 发布:禁止软件开机启动 编辑:程序博客网 时间:2024/06/18 18:29

题目:

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.

解法一:

Tips:使用queue来存储,方便在出现重复元素时,对元素进行删除,并不影响顺序有一个点需要主要,在判断到重复元素时,进行poll操作,记得再把重复元素重新加入。int result = 0;Queue<Character> queue = new LinkedList<>();for(int i=0;i<s.length();i++){    if(queue.contains(s.charAt(i))){        result = Math.max(result,queue.size());        while(queue.size()!=0){            char temp = queue.poll();            if(temp==s.charAt(i)){                queue.add(s.charAt(i));                break;            }        }    }else{        queue.add(s.charAt(i));    }}return Math.max(queue.size(),result);

解法二:
解法二和解法一的思路一致,但由于使用了set,限制了重复元素,不需使用双重for循环

int i = 0, j = 0, max = 0;        Set<Character> set = new HashSet<>();        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;

解法三:动规思路
由于自己现在还没有对动归有系统的学习
希望过段时间总结之后再来分析,先贴别人的代码

int lengthOfLongestSubstring(string s) {    // for ASCII char sequence, use this as a hashmap    vector<int> charIndex(256, -1);    int longest = 0, m = 0;    for (int i = 0; i < s.length(); i++) {        m = max(charIndex[s[i]] + 1, m);            // automatically takes care of -1 case        charIndex[s[i]] = i;        longest = max(longest, i - m + 1);    }    return longest;}
阅读全文
0 0
原创粉丝点击