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

3. Longest Substring Without Repeating Characters

时间:2016-05-04 18:43:34      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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.

给出一个字符串,求最长子串(不能有重复字符)的长度。

思路是使用双指针,记录区间内某个字符是否出现,如果没有出现就更新当前的最长长度(mx),否则从前端开始缩短字符串,直到没有重复的为止,代码如下:

    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        vector<bool> view(256,false);
        int mx = 0;
        int i = 0; int j = 0;
        for (; j<n; ++j)
        {
            if (view[s[j]])
            {
              for(; s[i]!=s[j]; ++i)
                 view[s[i]] = false;
              view[s[i]] = false;
         ++i; } else mx = max(mx, j-i+1);
       view[s[j]] = true; }
return mx; }

时间复杂度是O(n).

3. Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/zhiguoxu/p/5459241.html

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