首页 > 其他 > 详细

3. Longest Substring Without Repeating Characters

时间:2019-04-16 17:01:52      阅读:114      评论:0      收藏:0      [点我收藏+]

leetcode 3.给定一字符串,求出最长不重复子串长度。

 

第一种方法就是穷举,计算每种情况,很容易想到,思路上很清晰很简单在此就不附上代码了

这里摘引一些好的做法:

HashSet(哈希表) 做一个sliding window(滑动窗口) (可参考相关链接)

java:
public
class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(); Set<Character> set = new HashSet<>(); int Max_len = 0, i = 0, j = 0; while (i < n && j < n) { if (!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); Max_len = Math.max(Max_len, j - i); } else { set.remove(s.charAt(i++)); } } return Max_len; } }

 

Java (using hashmap)

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [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;
    }
}

 

Java(ASII 128)

前面的实现都没有关于字符串的字符集的假设。如果我们知道字符集相当小,我们可以用整数数组替换Map作为直接访问表。常用的table有:

  • int[26] for Letters ‘a‘ - ‘z‘ or ‘A‘ - ‘Z‘
  • int[128] for ASCII
  • int[256] for Extended ASCII
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;
    }
}

 

从本题中学到了什么?

        了解到了hashset与hashmap,sliding window 在解题中的基础应用。

相关学习链接推荐如下:

http://www.cnblogs.com/skywang12345/p/3311252.html

https://www.cnblogs.com/mozi-song/p/9567163.html

 

3. Longest Substring Without Repeating Characters

原文:https://www.cnblogs.com/liuzhuan-xingyun/p/10718213.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!