BAT面試算法進階(4)- 無重複字符的最長子串(滑動法優化+ASCII碼法)

一.算法題

  • 題目

Given a string, find the length of the longest substring without repeating characters.java

  • Example
  • Given "abcabcbb", the answer is "abc", which the length is 3.
  • Given "bbbbb", the answer is "b", with the length of 1.
  • Given "pwwkew", the answer is "wke", with the length of
  • Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

二.算法題解讀

  • 題目大意:給定一個字符串,找出不含有重複字符的最長子串的長度web

  • 解讀Example面試

  • 給定"abcabcbb",沒有重複字符的最長子串是"abc",那麼長度就是3
  • 給定"bbbbb",最長子串就是"b",長度就是1
  • 給定pwwkew,最長子串就是"wke",長度爲3,
  • ==注意,==必須是一個子串."pwke",是子序列,而不是子串

三.優化"滑動窗口"解決思路

到底如何在滑動窗口方法上優化了? 實際上咱們能夠若是採用進一步優化,能夠達到只須要N次便可計算成功.咱們能夠定義字符到索引映射.而不是使用集合來判斷這個字符的存在與否.當遇到重複的字符時,咱們便可跳過該滑動窗口.算法

也能夠理解爲,若是s[j][i,j)的範圍內有與j'重複的字符.咱們不須要逐漸增長i.而是直接跳過[i,j']範圍內的全部元素.並將i變成爲j'+1就能夠作到.數組

四.代碼實現

java codebash

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
       //獲取當前字符索引
        Map<Character, Integer> map = new HashMap<>();         
        //修改[i,j]的範圍       
         for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}
複製代碼

五.使用ASCII 128碼 思路

字符串,其實由字符構成.而字符則能夠用ASC碼來替代.如此,咱們能夠用整數數組做爲直接訪問表來替換Map.學習

經常使用表以下:優化

int [26],用於表示字母 "a" - "z" 或 "A" - "Z";ui

int [128],用於表示ASCII碼spa

int [256],用於表示擴展ASCII碼

A = 65, a = 97

Enter your image description here:

六.代碼實現

java code

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        int[] index = new int[128];         
        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;
    }
}
複製代碼

做爲一個開發者,有一個學習的氛圍跟一個交流圈子特別重要這是一個個人iOS交流羣:551346706,無論你是小白仍是大牛歡迎入駐 ,分享BAT,阿里面試題、面試經驗,討論技術, 你們一塊兒交流學習成長!

下面是小編給你們推薦的面試資料哦!

Enter your image description here:

Enter your image description here:
相關文章
相關標籤/搜索