码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Longest Substring Without Repeating Characters

时间:2016-10-14 07:04:04      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

 

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;
    }
};

 

[LintCode] Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/grandyang/p/5958762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!