Longest Substring Without Repeating Characters
来源:互联网 发布:孢子mac下载 编辑:程序博客网 时间:2024/05/16 19:49
Question:
Find the longest sub-string without repeating characters. For example, if the given string is "abcdcefg", the longest sub-stringwithout repeating characters is "dcefg".
Analysis:
In order to check whether the character repeats or not, the common approach is to build a hash table. When the character appears for the first time, we set its value in the hash table to be true, therefore, when that character appears again, we know the current sub-string will have duplicated character if we continue.
When we continue with a new sub-sting, we should set the hash table value of the previous characters to be false (but not all of them, see the code below), and compare the current sub-string with the temp longest sub-string.
Code:
public class Test {public static void main(String[] args) {Test t = new Test();System.out.println(t.lengthOfLongestSubstring("abcdcef"));}int lengthOfLongestSubstring(String s) { int n = s.length(); int i = 0, j = 0; int maxLen = 0; boolean exist[] = new boolean[256]; for (int k = 0; k < 255; k++) { exist[k] = false; } while (j < n) { if (exist[s.charAt(j)]) { maxLen = max(maxLen, j - i); while (s.charAt(i) != s.charAt(j)) { exist[s.charAt(i)] = false; i++; } i++; j++; } else { exist[s.charAt(j)] = true; j++; } } maxLen = max(maxLen, n - i - 1); return maxLen;}int max(int a, int b) {return a > b ? a : b;}}
From: http://blog.csdn.net/beiyetengqing
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- 网络整合营销之策略
- printf和scanf的缺陷,标准流类、文件流类、串流类,I/O成员函数
- X64的调用约定
- poj2367 Genealogical tree
- shellapi.h(55) : error C2065: 'HDROP' : undeclared identifier
- Longest Substring Without Repeating Characters
- 【UML】UML几种图的绘制
- publishing failed with multiple errors
- 名人问题 (Celebrity problem)
- 一道收集优惠券的面试题
- 求两个数组的交集
- 求两个排序数组的并集
- 【UML】案例分析:机场运作系统
- CentOS卸载OpenJDK并安装Sun JDK