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.
我的基本思路:
用max记录到目前为止数到的子字符串中最长的长度;
用current记录当前数到的子字符串的长度;
用startPos记录当前数到的子字符串的起始位置;
用sucket[a]表示字符a是否已存在与子字符串中(因为总共只有256中可能的字符,因此直接存在一个长为256的数组中即可,1表示已存在,0表示不存在);
每操作一次就更新一次max;
如果字符串s为空,直接返回0;
首先将s第一个字符看作当前子字符串,startPos = 0, current = 1;
用 i 表示当前子字符串的结束坐标,从 1 移到 s 的最后一个字符;
在移动过程中,如果 i 处字符已出现,将startPos 移到子字符串中和 i 处字符相同的字符位置下一位并更新current;
循环结束后max即为所求。
我的代码如下:
class Solution {public: int lengthOfLongestSubstring(string s) { if (s.length() == 0) return 0; // bucket[a] means whether the character a is already in the substring // 1 means yes, 0 means not int* bucket = new int[256]; for (int i = 0; i < 256; i++) bucket[i] = 0; bucket[s[0]] = 1; //max stores the max length of all substrings //current stores the length of current substring //startPos stores the start position of current substring int max = 1, current = 1, startPos = 0; for (int i = 1; i < s.length(); i++) { // refresh the value of max if (current > max) max = current; // if the character s[i] is already in the substring if (bucket[s[i]]) { for (int j = startPos; j < i; j++) { startPos++; if (s[j] == s[i]) break; bucket[s[j]] = 0; current--; } } else { bucket[s[i]] = 1; current++; } } if (current > max) max = current; return max; }};