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:
相关文章
相关标签/搜索