LeetCode第三題之無重複字元的最長子串
阿新 • • 發佈:2019-01-09
給定一個字串,找出不含有重複字元的最長子串的長度。
示例:
給定 "abcabcbb"
,沒有重複字元的最長子串是 "abc"
,那麼長度就是3。
給定 "bbbbb"
,最長的子串就是 "b"
,長度是1。
給定 "pwwkew"
,最長子串是 "wke"
,長度是3。請注意答案必須是一個子串,"pwke"
是 子序列 而不是子串。
思路一:直接暴力求解,把所有的可能子串遍歷出來,得出長度最大的那個。
public static int lengthOfLongestSubstring1(String s) { int maxlength = 0; int strLength = s.length(); for(int i=0;i<strLength;i++) { StringBuilder sBuilder = new StringBuilder(); sBuilder.append(s.charAt(i)); for(int j=i+1;j<strLength;j++) { if(sBuilder.indexOf(""+s.charAt(j))!=-1) { break; }else { sBuilder.append(s.charAt(j)); } } maxlength = (maxlength>sBuilder.length())?maxlength:sBuilder.length(); } return maxlength; }
思路二:空間換時間,查詢重複值可以用map或者set等,這裡使用hashset(底層也是hashmap),時間複雜度O(N).
public static int lengthOfLongestSubstring2(String s) { int maxlength = 0; int strLength = s.length(); int left=0,right=0; HashSet<Character> hashSet = new HashSet<>(); while (left<strLength&&right<strLength) { if(hashSet.contains(s.charAt(right))) { hashSet.remove(s.charAt(left)); left++; }else { hashSet.add(s.charAt(right)); right++; maxlength = Math.max(maxlength, right - left); } } return maxlength; }
思路三:以上兩個方法都是一個一個的遍歷,其實中間可以省掉很多步,當查到第一個重複字元時,最外層再次查詢的時候可以從第一個重複字元的下一個開始。例如,給定字串“abcbdc”,當查到b這個重複字元時,下一次遍歷可以直接從d開始。
GitHub地址:https://github.com/xckNull/Algorithms-introductionpublic static int lengthOfLongestSubstring3(String s) { int maxlength = 0; int strLength = s.length(); HashMap<Character, Integer> hashMap = new HashMap<>(); int left=0,right=0; while (left<strLength&&right<strLength) { if(hashMap.containsKey(s.charAt(right))) { left = Math.max(hashMap.get(s.charAt(right))+1, left); } hashMap.put(s.charAt(right), right); right++; maxlength = Math.max(maxlength, right - left); } return maxlength; }