LeetCode Longest Substring Without Repeating Characters C++

来源:互联网 发布:linux tail 显示行号 编辑:程序博客网 时间:2024/06/15 07:15
#include <iostream>#include<string>#include <map>using namespace std;/*        Problom:        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.        by:crazys_popcorn@126.com           date: 2017-8-2 8:27*/class Solution {public:    int lengthOfLongestSubstring(string s)     {        std::map<int,int >  _num;        _num.clear();        int max_len = 0;        int pre_len = 0;        for (int i = 0; i < s.length(); i++)        {            int  j = i + 1;            _num[s[i]];            pre_len = 1;            for (; j < s.length(); j++)            {                std::map<int, int >::const_iterator it = _num.find(s[j]);                if (it != _num.end())                {                    if (pre_len > max_len)                    {                        max_len = pre_len;                    }                    _num.clear();                    pre_len = 0;                    break;                }                else                {                    _num[s[j]];                    pre_len++;                }            }            if (pre_len > max_len)            {                max_len = pre_len;            }        }           return max_len;    }};void main(){    Solution s1;    std::string _str = "c";    std::cout << s1.lengthOfLongestSubstring(_str) << std::endl;    system("pause");}
阅读全文
0 0