給定一個string,請輸出在這之中不含同樣字元最長的子字串的長度。
範例:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
以一個陣列為零來去判斷是否出現過,若碰到出現過的則判斷比目前最長的字串誰較長。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ascii[256];
int ans=0;
for(int i=0;i<s.length();i++)
{
int len=1;
memset(ascii, 0, sizeof(ascii));
ascii[int(s[i])]=1;
for(int j=i+1;j<s.length();j++)
{
if(ascii[int(s[j])])
{
if(len>ans)
ans=len;
break;
}
ascii[int(s[j])]=1;
len++;
if(j==s.length()-1&&len>ans)
ans=len;
}
}
if(ans==0)
ans=s.length();
return ans;
}
};
其實在我寫完後,我才第一次發現原來Leetcode有給Solution?
好了,不廢話了,我去唸英文。