[LintCode] Longest Substring Without Repeating Characters

简介:

Given a string, find the length of the longest substring without repeating characters.

Example

For example, the longest substring without repeating letters for"abcabcbb" is "abc", which the length is 3.

For "bbbbb" the longest substring is "b", with the length of 1.

Challenge 

O(n) time

LeetCode上的原题,请参见我之前的博客Longest Substring Without Repeating Characters

解法一:

class Solution {
public:
    /**
     * @param s: a string
     * @return: an integer 
     */
    int lengthOfLongestSubstring(string s) {
        int res = 0, left = -1;
        vector<int> m(256, -1);
        for (int i = 0; i < s.size(); ++i) {
            left = max(left, m[s[i]]);
            m[s[i]] = i;
            res = max(res, i - left);
        }
        return res;
    }
};

解法二:

class Solution {
public:
    /**
     * @param s: a string
     * @return: an integer 
     */
    int lengthOfLongestSubstring(string s) {
        int res = 0, left = 0, right = 0;
        unordered_set<char> st;
        while (right < s.size()) {
            if (!st.count(s[right])) {
                st.insert(s[right++]);
                res = max(res, (int)st.size());
            } else {
                st.erase(s[left++]);
            }
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:[LintCode] Longest Substring Without Repeating Characters,如需转载请自行联系原博主。

相关文章
Leetcode 516. Longest Palindromic Subsequence
找到一个字符串的最长回文子序列,这里注意回文子串和回文序列的区别。子序列不要求连续,子串(substring)是要求连续的。leetcode 5. Longest Palindromic Substring就是求连续子串的。
49 0
|
Java
Leetcode 3. Longest Substring Without Repeating Characters
此题题意是找出一个不包含相同字母的最长子串,题目给出了两个例子来说明题意,但这两个例子具有误导性,让你误以为字符串中只有小写字母。还好我是心机boy,我把大写字母的情况也给考虑进去了,不过。。。。字符串里竟然有特殊字符,于是贡献了一次wrong answer,这次我把ascii字符表都考虑进去,然后就没问题了。这个故事告诫我们在编程处理问题的时候一定要注意输入数据的范围,面试中可以和面试官去确认数据范围,也能显得你比较严谨。
50 3
LeetCode 424. Longest Repeating Character Replacem
给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。
104 0
LeetCode 424. Longest Repeating Character Replacem
|
算法
LeetCode 300. Longest Increasing Subsequence
给定一个无序的整数数组,找到其中最长上升子序列的长度。
53 0
LeetCode 300. Longest Increasing Subsequence
|
索引
Leetcode-Medium 5. Longest Palindromic Substring
Leetcode-Medium 5. Longest Palindromic Substring
115 0
[LeetCode]--5. Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 我用的是中心扩展法 因为
1229 0
|
算法
[LeetCode]--3. Longest Substring Without Repeating Characters
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 i
1465 0