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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

LeetCode算法入门- Longest Substring Without Repeating Characters-day4

發布時間:2025/3/12 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode算法入门- Longest Substring Without Repeating Characters-day4 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

LeetCode算法入門- Longest Substring Without Repeating Characters-day4

Longest Substring Without Repeating Characters

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

Example 1:

Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:

Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:

Input: “pwwkew”
Output: 3
Explanation: 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.

方法一:暴力破解法:時間復雜度為:0(n^3)

class Solution {public int lengthOfLongestSubstring(String s) {int n = s.length();int ans = 0;for(int i = 0; i < n; i++){for(int j = i+1; j <= n; j++){if(allUnique(s, i, j))//取最大值ans = Math.max(ans,j-i);}}return ans;}public static boolean allUnique(String s, int start, int end){Set<Character> set = new HashSet<>();for(int i = start; i < end; i++){Character ch = s.charAt(i);//通過set數據結構的contains方法來判斷是否重復if(set.contains(ch))return false;set.add(ch);}return true;} }

方法二:基本思路為:i,j都是從0開始,當s.charAt(j)不在set中的時候,j++,同時set.add(s.charAt(j));當s.charAt(j)在set當中時,i++,同時移除掉s.charAt(i),注意i+1加到set中不含s.charAt(j)為止。取出ans與j-i之間的最大值即可。
利用set數據結構

class Solution {public int lengthOfLongestSubstring(String s) {int n = s.length();Set<Character> set =new HashSet<>();int ans = 0;int i = 0;int j = 0;while(i < n && j <n){if(!set.contains(s.charAt(j))){set.add(s.charAt(j++));ans = Math.max(ans, j - i);}else{set.remove(s.charAt(i++));}}return ans;} }

總結

以上是生活随笔為你收集整理的LeetCode算法入门- Longest Substring Without Repeating Characters-day4的全部內容,希望文章能夠幫你解決所遇到的問題。

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