LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj
題目描述:


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.


就是從一個字串中找出最長的,沒有重複字元的字串。


思路:
遍曆字串,使用雜湊表對每個字元逐個儲存:[字元,位置],如果遇到重複:
1.更新當前位置的最大長度
2.從當前字元上一次出現的位置的下一個字元開始,繼續遍曆
3.清空雜湊表


後來發現清空雜湊表的操作效能損耗太大,沒法通過測試資料。
使用一個bool數組keys來代替雜湊的作用(每一位初始化為false),並使用start變數來代替上一次重複字元的位置(初始化為0):
1.使用長度為256的數組,對於字串s中的每個字元逐個遍曆,判斷當前s[i]是否在keys[s[i]]已經出現過,如果沒有出現:
keys[s[i]]設為true
如果已經出現:
1.比較i到start的距離與當前的最大長度,取最大者
2.將keys[start,i]重設為false,從s[start+1]的位置繼續往下走




實現代碼:


public class Solution {    public int LengthOfLongestSubstring(string s) {       if(string.IsNullOrWhiteSpace(s)){return 0;    }        var keys = new bool[256];         int max = 0;    int start = 0;         for (int i = 0; i < s.Length; i++) {    var current = s[i];    if (keys[current]) {    max = Math.Max(max, i - start);    for (int k = start; k < i; k++) {    if (s[k] == current) {    start = k + 1;     break;    }    keys[s[k]] = false;    }    } else {    keys[current] = true;    }    }         max = Math.Max(s.Length - start, max);         return max;    }}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

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