您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:哈希:Longest Substring Without Repeating Characters(003)

2016-06-25 13:39 507 查看

题目

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.

算法

数组hash

O(N)

申请数组,记录当前字符出现的最近位置,一遍算过去,更新左边界,利用最边界计算;

const int N = 300;

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxlen = 0,left = 0;
int sz = s.length();
int prev
;
memset(prev,-1,sizeof(prev));

for(int i=0;i<sz;i++){
if(prev[s[i]]>=left)
left=prev[s[i]]+1;
prev[s[i]] = i;
maxlen = max(maxlen,i-left+1);

}

return maxlen;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: