[LeetCode] Longest substring without repeated characters
来源:互联网 发布:grub2 引导linux 编辑:程序博客网 时间:2024/05/17 06:07
这题的idea就是从前往后扫,用个hashtable(其实是数组)把上次出现过的位置记下来,遇到出现过的,就从上次出现过的地方开始往下算。 具体实现细节对于新手还是有些坑,比如我刚开始就觉得从新的start开始扫的话,要把hashtable重新initialize,但实际上加一个条件就能避免。另外最长substring出现在最后也有点费思量。还有hashtable要initialize 为-1等也需要注意。 public class Solution { public int lengthOfLongestSubstring(String s) { int start = 0, max = 0; int [] last = new int[256]; Arrays.fill(last, -1); //initialize as -1, since 0 is also a valid position.
for (int i = 0; i < s.length(); i++){ int c = s.charAt(i); if (last[c] >= start){ //with this check, you don't need to count the appreance again. max = Math.max(max, i - start); start = last[c] + 1; } last[c] = i; } max = Math.max(max, s.length() - start); //don't forget the last character, like "abcd" return max; }
}
0 0
- [LeetCode] Longest substring without repeated characters
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- 链表合并
- Meeting --- Codeforces
- IE 兼容性改造Js点滴积累
- 扩展欧几里得
- 【堆积如山的未解决题目OTZ】
- [LeetCode] Longest substring without repeated characters
- 技术普及帖:你刚才在淘宝上买了一件东西
- Ubuntu 不显示时间了
- js对象创建的方式及其优势和不足7
- DP--Longest Valid Parentheses
- poj3160(Tarjan+Spfa)
- WARNING: Phonon needs QCoreApplication::applicationName to be set to export audio output names throu
- linux c/c++ 后台开发常用组件之:高性能阻塞队列
- 设计模式之装饰模式