日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leet Code OJ 3. Longest Substring Without Repeating Characters

發布時間:2024/2/28 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leet Code OJ 3. Longest Substring Without Repeating Characters 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

翻譯

給定一個字符串,找到最長的子串的長度,這個子串不存在重復的字符。
例如:
輸入”abcabcbb”, 符合條件的子串就是”abc”, 長度為3。

輸入”bbbbb”, 符合條件的子串就是”b”, 長度為1

輸入”pwwkew”, 符合條件的子串就是”wke”, 長度為3。提示:要求必須是子串,例如”pwke” 是一個子序列但不是一個子串。

分析

遍歷一遍,記錄符合條件的長度count。如果遇到相同的字符,則從左往右remove直到移除掉那個相同的字符。

Java版代碼(時間復雜度O(n),空間復雜度O(n)):

public class Solution {public int lengthOfLongestSubstring(String s) {Map<Character, Integer> map = new HashMap<Character, Integer>();char[] charArr = s.toCharArray();int max = 0;int count = 0;for (int i = 0; i < charArr.length; i++) {Integer last = map.get(charArr[i]);if (last == null) {count++;if (count > max) {max = count;}} else {int start=i-count;for(int j=start;j<last;j++){map.remove(charArr[j]);count--;}}map.put(charArr[i], i);}return max;} }

總結

以上是生活随笔為你收集整理的Leet Code OJ 3. Longest Substring Without Repeating Characters的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。