【Leet Code】Longest Substring Without Repeating Characters

來源:互聯網
上載者:User

標籤:遍曆   substring   

Longest Substring Without Repeating Characters Total Accepted: 20506 Total Submissions: 92223My Submissions

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.


這題目有點兒坑啊,一開始沒想明白,過一會兒才看懂題目要求,題目是找沒有重複字元的最長子字串,呵呵。也沒想到什麼好辦法,只能while了:

class Solution {public:int lengthOfLongestSubstring(string s) {bool state[256];memset(state, false, sizeof(state));int ans = 0, l = 0, r = 0;while (r < s.length()) {while (r < s.length() && state[ s[r] ] == false) {state[ s[r++] ] = true;}ans = max(ans, r - l);while (l < r && s[l] != s[r]){state[s[l++]] = false;}l++, r++;}return ans;}};
這個方法很明顯了,用while裡面嵌套while,可以說遍曆的大部分字串了。不過,有大神的代碼如下:

class Solution {public:int pos[256];int lengthOfLongestSubstring(string s){// IMPORTANT: Please reset any member data you declared, as// the same Solution instance will be reused for each test case.for (int i = 0; i < 256; ++i)pos[i] = -1;int stp = -1, sz = s.size(), res = 0;for (int i = 0; i < sz; ++i){if (pos[s[i]] >= stp){  //update posistionstp = pos[s[i]] + 1;}pos[s[i]] = i;res = max(res, i - stp + 1);}return res;}};//whose code is shorter than mine? Please notify me! I want to meet shorter codes!
大神就是大神,居然把找到的最近重複的字元的位置給記錄下來了,佩服佩服,更讓人為之瘋狂的是,居然還在最後加上了:

<span style="font-size:18px;color:#ff0000;"><strong>whose code is shorter than mine? Please notify me! I want to meet shorter codes!</strong></span>
哈哈,厲害厲害!



【Leet Code】Longest Substring Without Repeating Characters

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.