美文网首页
[LeetCode] 003.Longest Substring

[LeetCode] 003.Longest Substring

作者: QyQiaoo | 来源:发表于2017-08-20 17:41 被阅读0次

    Problem description

    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.

    Code (C++)

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            
            int len = s.length();
            set<char> co;
            
            int left = 0;
            int right = 0;
            int res = 0;
            
            while(right < len) {
                if(co.find(s[right]) != co.end()) {
                    co.erase(s[left]);
                    left++;
                } else {
                    co.insert(s[right]);
                    right++;
                    res = res > right - left ? res : right - left;
                }
            }
            return res;
        }
    };
    

    Code (Java)

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            
            int len = s.length();
            Set<Character> co = new HashSet<Character>();
            
            int left = 0;
            int right = 0;
            int res = 0;
            
            while(right < len) {
                if(co.contains(s.charAt(right)) == true) {
                    co.remove(s.charAt(left));
                    left++;
                } else {
                    co.add(s.charAt(right));
                    right++;
                    res = Math.max(res, right - left);
                }
            }
            return res;
        }
    }
    

    Analysis

    • 注意解题思路。

    相关文章

      网友评论

          本文标题:[LeetCode] 003.Longest Substring

          本文链接:https://www.haomeiwen.com/subject/wlgfdxtx.html