Leetcode--lengthOfLongestSubstring

來源:互聯網
上載者:User

標籤:substring   sub   簡單   class   移動   log   bst   record   leetcode   

這道題很簡單,我的思路是設定一個數組儲存字元,然後設定兩個浮標,右浮標不斷向後移動,如果浮標所在字元在數組中有出現,就儲存長度,然後把左字元的位置設定為出現重複字元的後一個位置,然後儲存長度,清空數組,接著不斷重複即可。

主要要解決的是檢測重複數組所費時間,如果單純使用數組,時間複雜度就是O(n2),可以使用hash表儲存字元,可以降低時間複雜度為O(n)

    static int lengthOfLongestSubstring(std::string s) {        if (s.length() == 0)            return 0;        int length = 1, length_2 = 0, record = 0;        map<char, int> temp;        for (int i = 0; i < s.length(); i++) {            if (temp.count(s[i]) != 0) {                if (i - temp[s[i]] + 1 > length_2)                    length_2 = length;                temp.clear();                i += temp[s[i]];                length = 0;                continue;            }            temp[s[i]] = i;            ++length;        }        if (length > length_2)            length_2 = length;        return length_2;    }};

還有Leetcode上提供了一個很好的解法,分享下

static int lengthOfLongestSubstring(string s) {        int n = s.length();        int i = 0, j = 0;        int maxLen = 0;        bool exist[256] = {false};        while (j < n) {            if (exist[s[j]]) {                maxLen = max(maxLen, j - i);                while (s[i] != s[j]) {                    exist[s[i]] = false;                    i++;                }                i++;                j++;            } else {                exist[s[j]] = true;                j++;            }        }        maxLen = max(maxLen, n - i);        return maxLen;    }

這個解法真的太巧妙了,設定左右兩個浮標,然後設定一個大小為256的bool數組,對應256個ascii碼。

妙處就是i和j都只把這個string從開始到結束遍曆了一遍。

本來寫了很長的講解 ,但是覺得說的太繁瑣了,實在是不太擅長向別人講知識。腦袋裡面能類比運行,但是就是講不出來,具體的大家可以運行單步調試一下,就可以體會到其中妙處

 

Leetcode--lengthOfLongestSubstring

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.