leetCode 第三題

題目詳情

在這裏插入圖片描述

思路分析

去重的問題首先應該想到的是set數據結構。其的思路就是去利用set來進行記錄當前的集合中是否有重複的元素。


class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> s1 = new HashSet<Character>();
		int len = s.length();
        int current =0;
        int maxLength = 0;
        int position = 0;
		while(current<len){
        	if(s1.contains(s.charAt(current))){
        		
        		while(s.charAt(position)!=s.charAt(current)&&position<current){
        			s1.remove(s.charAt(position));
        			position++;
        		}
        		position++;
        		current++;
        		continue;
        	}else{
        		s1.add(s.charAt(current));
        		
        		if((current-position+1)>maxLength){
        			maxLength = current-position+1;
        		}
        	}
			current++;
      }
        return maxLength;
    }
    
}

同樣的思路,可以改進寫法寫成

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            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;
    }
}

還有一種比較討巧的方法,就是利用數組來記錄出現的次數,下一次出現同樣的元素,把其index進行覆蓋就行了

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        int[] index = new int[128]; // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            i = Math.max(index[s.charAt(j)], i);
            ans = Math.max(ans, j - i + 1);
            index[s.charAt(j)] = j + 1;  //這個地方進行下標的覆蓋,非常高效
        }
        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章