2019-02-22-算法-进化
生活随笔
收集整理的這篇文章主要介紹了
2019-02-22-算法-进化
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述:
給定一個字符串,請你找出其中不含有重復字符的 最長子串 的長度。
示例 1:
示例 2:
輸入: "bbbbb" 輸出: 1 解釋: 因為無重復字符的最長子串是 "b",所以其長度為 1。示例 3:
輸入: "pwwkew" 輸出: 3 解釋: 因為無重復字符的最長子串是 "wke",所以其長度為 3。 請注意,你的答案必須是 子串 的長度,"pwke" 是一個子序列,不是子串。我的第一版解決方案:
public static int lengthOfLongestSubstring(String s) {if(s==null || s == "") {return 0;}int longest=0;Set<Character> set = new HashSet<Character>();for(int i=0;i<s.length();i++) {set.clear();int tLongest =0;for(int j=i;j<s.length();j++) {if(set.contains(s.charAt(j))) {longest = (tLongest > longest)?tLongest:longest;break;}else {set.add(s.charAt(j));tLongest ++;}}longest = (tLongest > longest)?tLongest:longest;}return longest;}參照標準答案調整后:
public static int lengthOfLongestSubstring(String s) {if(s==null || s == "") {return 0;}int n = s.length();int i=0,j=0, max=0;Set<Character> set = new HashSet<Character>();while(i<n && j<n) {if(set.contains(s.charAt(j))) {set.remove(s.charAt(i++));}else {set.add(s.charAt(j++));max = Math.max(max, j-i);}}return max;}輔助空間基本不變,但是時間從O(n `2)到O(n),有了數(shù)量級上的提升。
主要使用了“滑動窗口”的概念([m,n)左閉右開),減少了重復的比較,提升了效率。
題庫地址:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
總結
以上是生活随笔為你收集整理的2019-02-22-算法-进化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java修炼之路——基础篇——数据类型
- 下一篇: 仙草粉的功效与作用、禁忌和食用方法