首页 > 其他 > 详细

LeetCode#3.Longest Substring Without Repeating Characters

时间:2016-05-31 22:11:32      阅读:118      评论:0      收藏:0      [点我收藏+]

题目

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.

思路

采用哈希的思想,建立数组,映射字符串,记录字符串每个字符出现的位置。

最长无重复子串肯定包含在两个重复字符之间,或者,没有重复时,从头到尾。

遇到重复字符(哈希数组中记录了一个位置),更新起始位置。

每前进一个位置,将最大值与当前位置与起始位置的差比较更新最大值。

代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);
        int maxLen = 0, start = -1;
        for (int i = 0; i != s.length(); i++) {
            if (dict[s[i]] > start)
                start = dict[s[i]];
            dict[s[i]] = i;
            maxLen = max(maxLen, i - start);
        }
        return maxLen;
    }
};

LeetCode#3.Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/yatesxu/p/5547539.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!