【LeetCode刷題記錄】3. 無重複字符的最長子串

題目描述:
在這裏插入圖片描述
題解:
一、暴力破解(時間複雜度:O(n3),空間複雜度:O(1),超出時間限制(TLE))
BF方法的思路比較簡單,逐個檢查所有的子字符串,看它是否不含有重複的字符。取不重複子字符串中長度最大的那個作爲結果輸出。
二、雙指針滑動窗口(時間複雜度:O(n2),空間複雜度:O(1))

int lengthOfLongestSubstringSlide(string s) {
 int i = 0, j = 0, len = 0, rst = 0;
 while (j < s.size()) {
  char c = s[j];
  for (int idx = i; idx < j; idx++) {
   if (c == s[idx]) {
    i = idx + 1;
    len = j - i;
    break;
   }
  }
  j++;
  len++;
  rst = rst > len ? rst : len;
 }
 return rst;
}

思路:每次檢查後指針指向的字符是否在前指針到後指針之間出現過,未出現,則後指針後移,長度+1,檢查、更新結果;出現,則前指針移至出現位置的下一位置,更新長度值,後指針後移,長度+1,檢查、更新結果。
三、哈希表優化方法二(時間複雜度:O(n),空間複雜度:O(n))

int lengthOfLongestSubstringSlideHash(string s) {
 int i = 0, j = 0, len = 0, rst = 0;
 unordered_map<char, int> record;
 while (j < s.size()) {
  char c = s[j];
  if (record.find(c) != record.end() && record[c] >= i)
  {
   i = record[c] + 1;
   len = j - i;
  }
  record[c] = j;
  j++;
  len++;
  rst = rst > len ? rst : len;
 }
 return rst;
}

使用哈希表,用空間換時間。
關於哈希表,參考:C++: map/hash_map/unordered_map

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章