标签:
题目描述:Longest Substring Without Repeating Characters
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. 是全部字符,还是a-z的英文字母?
2. 找到相同的字符后,如何处理接下来的字符?如果是在第i和j个位置发现了同一个字符,那么接下来字符串的起始位置应该是i+1(假设i < j);
3. 时间复杂度是O(n)。
代码如下:
class Solution { public: int lengthOfLongestSubstring(string s) { const int ASCII_MAX = 256; int charMap[ASCII_MAX]; //记录字符上次出现的位置 int start = 0; //记录当前子串的起始位置 int max_len = 0; fill(charMap, charMap + ASCII_MAX, -1); //填充为-1 for(int i = 0; i < s.size(); i++){ if(charMap[s.at(i)] >= start){ max_len = max(i - start, max_len); start = charMap[s.at(i)] + 1; } charMap[s.at(i)] = i; } return max((int)s.size() - start, max_len); //包括全不相同的情况 } };
LeetCode 003 Longest Substring Without Repeating Characters
标签:
原文地址:http://www.cnblogs.com/510602159-Yano/p/4244370.html