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.
題目描述:要求找到字符串中最長的子串的長度
代碼如下:
class
Solution {
public:
int lengthOfLongestSubstring(string s) { //
int loc[128]; //以字符的值爲下標,ASCii碼錶總共是128個字符
memset(loc,-1,sizeof(loc)); //申請sizeof(loc)個空間,並將loc數組的值都初始化爲-1
int index=-1; //保存子串出現的第一個位置
int max=0; //保存子串的長度
for(int i=0;i<s.size();i++){
if(loc[s[i]]>index){ //如果字符串s[i]出現過,則子串第一次出現的位置修改爲上一次這字符出現的位置
index=loc[s[i]];
}
if(i-index>max){ //字串的長度即爲當前下標減去子串第一個字符出現的位置,與max進行比較,
max=i-index;
}
loc[s[i]]=i; //記錄字符出現的位置
}
return max;
}
};
時間複雜度爲O(n)。