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;}
}