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.翻譯:
給定一個字符串威鹿,找出沒有重復(fù)字符的最長子字符串的長度匈仗。
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時候,發(fā)現(xiàn)自己對這個函數(shù)的理解原來是有問題的,正常是對字符孤页,但是經(jīng)常會看到針對int數(shù)組的初始化:
int last[255]; memset(last, -1, sizeof last);
或者
int last[255]; memset(last, 0, sizeof last);
,以上的使用方式都是正確的骨杂。我剛開始寫的時候?qū)懗闪巳缦碌?strong>錯誤形式:
int last[255]; memset(last, -1, sizeof(last)/sizeof(int);
用debug模式迅脐,發(fā)現(xiàn)last數(shù)組并不是說有的都被初始化為-1娃肿,后面想了下,memset應(yīng)該是按照指針類型的字節(jié)數(shù)初始化黍衙,一個int一般是4個字節(jié)或者8個字節(jié)泥畅,如果我寫成
sizeof(last)/sizeof(int)
得到是實際的數(shù)組個數(shù),memset做處理就會少初始化了琅翻。?
?