您的位置:首页 > 其它

[leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】

2015-09-15 10:47 706 查看

Longest Substring Without Repeating Characters My Submissions Question Solution

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.

题意:遍历字符串,当前字符在遍历过的字符串中出现过时,将子串的头+1。

构造一个256长的标记数组,初始化为-1,代表askii码(总共256个)全部都没有出现过,若出现过就标记为当前位置。

class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int locs[256];//保存字符上一次出现的位置
memset(locs, -1, sizeof(locs));

int idx = -1, max = 0;//idx为当前子串的开始位置-1
for (int i = 0; i < s.size(); i++)
{
if (locs[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
{
idx = locs[s[i]];
}

if (i - idx > max)
{
max = i - idx;
}

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