[LeetCode] 003.Longest Substring Without Repeating Characters (C++/Java)

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

  • 注意解题思路。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,993评论 0 23
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,938评论 0 0
  • 我的意中人是个盖世英雄 总有一天他会身穿黄金甲 越过塔穿过草丛顺便偷蓝 过来娶你 的狗命 “死猴子我们再来决一死战...
    颜JK阅读 186评论 0 0
  • 爱你。 是冒险。 是放荡。是隐藏不住的惊喜。 你在的时候 。爱你。你不在的手边的时候。手想你。 人有两种。是你。不...
    BurningU阅读 111评论 0 0
  • 有僧人问夹山善会禅师:“祖意和教意是前人所立,和尚为什么说没有这些东西?” 夹山说:“三年不食饭,目前无饥人。” ...
    心灵环保阅读 2,443评论 0 2