Description
原文:
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.翻譯:
給定一個字符串,找出沒有重復字符的最長子字符串的長度。
Solution
class Solution { public: int lengthOfLongestSubstring(string s) { int ans = 0, left = 0, len = s.length(); int last[255]; memset(last, -1, sizeof last); for (int i = 0; i < len; ++i) { if (last[s[i]] >= left) left = last[s[i]] + 1; last[s[i]] = i; ans = max(ans, i - left + 1); } return ans; } };
Conclusion
這個題目的意思理解了很久
使用memset時候,發現自己對這個函數的理解原來是有問題的,正常是對字符,但是經常會看到針對int數組的初始化:
int last[255]; memset(last, -1, sizeof last);
或者
int last[255]; memset(last, 0, sizeof last);
,以上的使用方式都是正確的。我剛開始寫的時候寫成了如下的錯誤形式:
int last[255]; memset(last, -1, sizeof(last)/sizeof(int);
用debug模式,發現last數組并不是說有的都被初始化為-1,后面想了下,memset應該是按照指針類型的字節數初始化,一個int一般是4個字節或者8個字節,如果我寫成
sizeof(last)/sizeof(int)
得到是實際的數組個數,memset做處理就會少初始化了。?
?