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數據結構
總結
以上是生活随笔為你收集整理的LeetCode算法入门- Longest Substring Without Repeating Characters-day4的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 内部类详解————静态内部类
- 下一篇: MATLAB电压不平衡,电力系统不对称故