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

LeetCode 3. Longest Substring Without Repeating

时间:2016-02-10 22:13:17      阅读:205      评论: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.

 

思路:

用一个map存放字符出现的position;用两个指针begin,end指向substr的首末;遇到相同字符时将begin移到该字符之前出现的后一位置,并更新该字符的position。

 

代码:C++ :

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.length() <= 1)
            return s.length();
        
        int begin = 0;
        int end = 0;
        map<char,int> mapping;
        int solve = 0;
        
        mapping[s[0]] = 0;
        while (end < s.length() - 1) {
            end++;
           if (mapping.find(s[end]) != mapping.end()) {
                int gap = end - begin;
                if (gap > solve)
                    solve = gap;
                begin = mapping[s[end]] + 1 > begin ? mapping[s[end]] + 1 : begin;
                mapping[s[end]] = end;
            }
            else
                mapping[s[end]] = end;
        }
        int gap = end - begin + 1;
        if (gap > solve)
            solve = gap;
        return solve;
    }
};

 

LeetCode 3. Longest Substring Without Repeating

标签:

原文地址:http://www.cnblogs.com/gavinxing/p/5186141.html

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