LeetCode - Longest Substring Without Repeating Characters

来源:互联网 发布:学生档案表sql查询 编辑:程序博客网 时间:2024/06/10 21:58

Question:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


用一个数组来存储每一个字符在字符串中的位置,数组的下标表示这个字符的ASCII码,元素表示其在字符串中的位置即可。如下图所示(转):


代码如下所示:

import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.Set;public class LeetCode3 {/** * Given a string, find the length of the longest substring without repeating characters.  * For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.  * For "bbbbb" the longest substring is "b", with the length of 1. * @param args */public static void main(String[] args) {// TODO Auto-generated method stubString s1 = "";String s2 = null;String s3 = "abebcdab";String s4 = "abcabcde";int length = lengthOfLongestSubstring(s3);System.out.println(length);}public static int lengthOfLongestSubstring(String s) {if (s == null) {return -1;}int length = s.length();if (length == 0) {return 0;}int[] countTable = new int[256];Arrays.fill(countTable, -1);int max = 1;int start = 0;int end = 1;countTable[s.charAt(0)] = 0;while (end < length) {// Has not reached a duplicate charif (countTable[s.charAt(end)] >= start) {start = countTable[s.charAt(end)] + 1;}max = Math.max(max, end - start + 1);countTable[s.charAt(end)] = end;end++;}return max;}}



0 0
原创粉丝点击