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

Longest Substring Without Repeating Characters

时间:2014-05-15 17:50:38      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

Given a string, find the length of the longest substring without repeating characters. 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.

思路:本题找出字符串中最长的不包含相同的字符的子字符串不包含相同的字符。可以使用hash表来解决这道题。主要思路就是使用两个头尾指针,尾指针不断往后搜索,当该字符在前面出现过了,记录字符的长度和最长结果,此时头指针不断往后搜索,同时记录的长度count要减一,直到头指针指向的字符与尾指针相同时结束搜索,同时头指针向后移动一位,记录访问过的字符,长度count加一。最后优化最长结果。

bubuko.com,布布扣
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n=s.size();
        if(n<=1)
            return n;
        int result=0;
        int count=0;
        int begin=0;
        vector<bool> charTable(256,false);
        for(int i=0;i<n;i++)
        {
            if(charTable[s[i]]==false)//前面字符没有出现过,false表示没有出现过。
            {
                charTable[s[i]]=true;
                count++;
            }
            else
            {
                result=max(result,count);
                while(true)
                {
                    charTable[s[begin]]=false;
                    count--;
                    if(s[begin]==s[i])
                        break;
                    begin++;
                }
                begin++;
                charTable[s[i]]=true;
                count++;
            }
        }
        result=max(result,count);
        return result;
    }
};
bubuko.com,布布扣

   这道题也可以使用STL中的hash_map解决。至于如何实现,待我熟悉hash_map便可进行。

Longest Substring Without Repeating Characters,布布扣,bubuko.com

Longest Substring Without Repeating Characters

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/awy-blog/p/3729876.html

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