题目描述: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); //包括全不相同的情况 } };
Java:
public int lengthOfLongestSubstring(String s) { final int SIZE = 256; int[] charMap = new int[SIZE]; int start = 0; int maxLen = 0; Arrays.fill(charMap, -1); for (int i = 0; i < s.length(); i++) { //每次记录一个字符最后出现的下标,如果大于start,就表明之前出现过 //start就设置为上次出现位置的下一个 if (charMap[s.charAt(i)] >= start) { maxLen = Math.max(i - start, maxLen); start = charMap[s.charAt(i)] + 1; } charMap[s.charAt(i)] = i; } return Math.max(maxLen, s.length() - start); }