首页 > 其他 > 详细

LeetCode 3. Longest Substring Without Repeating

时间:2016-02-10 22:12:09      阅读:267      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!