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

Longest Substring Without Repeating Characters

时间:2015-04-05 21:54:11      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

今天清明,再补一篇

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.

input:abcabcbb

output:abc

代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, int> str_map;
        int maxlen = 0, flag = -1;
        for (int i = 0; i < s.size(); i++){
            if (!str_map.count(s[i])){
                str_map.insert(make_pair(s[i], -1));
            }
        }
        for (int i = 0; i < s.size(); i++){
            if (str_map[s[i]]>flag)
                flag=str_map[s[i]];
            if (i - flag > maxlen)
                maxlen = i - flag;
            str_map[s[i]] = i;
        }
        return maxlen;
    }
};

 

Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/Scorpio989/p/4394801.html

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