iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 9
0
自我挑戰組

有志者,事竟成。系列 第 9

Day9 第三十三題 LeetCode #3 Longest Substring Without Repeating Characters

題目描述

給定一個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?
好了,不廢話了,我去唸英文。


上一篇
Day8 第三十二題 LeetCode #2 Add Two Numbers
下一篇
Day10 第三十四題LeetCode #4 Median of Two Sorted Arrays
系列文
有志者,事竟成。19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言