您好,登錄后才能下訂單哦!
3. Longest Substring Without Repeating Characters
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.
題意:
給定一個字符串,找出最長的無重復的連續字串。就比如"pwwkew"的最長無重復連續字串是"wke"。
最易想到的方法就是字符串逐一開始查找,第一個字符串找到最長的字串,依次找出,取最大值即可。
由于有256個字符,故定義了個257長度的數組,足以存下所有字符。
思路
1)定義字符數組,并把256個的值都置為零。
2)逐個查找字符,如果未出現過,即把該下標對應的數組值置為一。若該下標值已經是一了,則返回,
3)重置全部數組元素元素為零,從下個下標開始繼續查找不重復字串。
4)返回最大字串長度即可。
#define CHARACTERS 257 int lengthOfLongestSubstring(char* s) { if ( !s ) { return 0; } int character[CHARACTERS] = { 0 }; int len = strlen(s); int cnt = 0; int size = 0; int maxLen = 0; int index = 0; for ( index = 0; index < len; index++ ) { size = 0; for ( cnt = 0; cnt < CHARACTERS; cnt++ ) { character[cnt] = 0; } for ( cnt = index; cnt < len; cnt++ ) { /* pwwkew */ int value = *(s + cnt); if ( character[value] == 0 ) { size += 1; character[value] = 1; } else { break; } } if ( size > maxLen ) { maxLen = size; } } return maxLen; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。