码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 003 Longest Substring Without Repeating Characters

时间:2015-04-23 23:22:16      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路一

由于题目给个tag为HashTable和Two Pointers

因此,我们可以定义一个HashTable,和两个Pointers,index1和index2,首先将String中元素不断添加进去,如果发现重复,则删除重复的元素和它之前的元素,它们在String中的位置分别用index1和index2进行标记,最后找到HashTable曾经的最大规模。这种思路的时间复杂度为O(n)代码如下

 1 public class Solution {
 2 static public int lengthOfLongestSubstring(String s) {
 3         char[] char1 = s.toCharArray();
 4         int longestLength = 0;
 5         int startIndex = 0;
 6         int lastIndex = 0;
 7         HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
 8         for (int i = 0; i < char1.length; i++) {
 9             if (hashMap.containsKey(char1[i])) {
10                 lastIndex = hashMap.get(char1[i]);
11                 if (longestLength < (i - startIndex)) {
12                     longestLength = i - startIndex;
13                 }
14                 for (int j = startIndex; j <= lastIndex; j++) {
15                     hashMap.remove(char1[j]);
16                 }
17                 startIndex = lastIndex+1;
18             }
19             hashMap.put(char1[i], i);
20         }
21         if(longestLength<char1.length-startIndex)
22             longestLength=char1.length-startIndex;
23         return longestLength;
24     }
25 }

但是,提交之后显示Time Limit Exceeded,看来时间复杂度还是太高,究其原因,在于中间有两个for循环,第二个for循环每进行一次删除都必须遍历一边,因此时间开销必然很大。

思路二:

其实每次添加过后,我们不一定要在HashMap中删除重复的元素,我们可以用一个指针记录需要删除元素的位置,如果出现重复元素,就把pointer置为重复元素最后一次出现的位置+1即可,判断之前最大的substring的长度和本次产生的substring长度的大小。之后将本元素添加进HashMap里面。当然,最后还需要判断下最后一次获得的子串的长度和之前长度的比较。

Java代码如下

public class Solution {
    	static public int lengthOfLongestSubstring(String s) {
		Map<Character, Integer> hashMap = new HashMap<Character, Integer>();
		int length = 0;
		int pointer = 0;
		for (int i = 0; i < s.length(); i++) {
			if (hashMap.containsKey(s.charAt(i))&& hashMap.get(s.charAt(i)) >= pointer) {
				length = Math.max(i-pointer, length);
				pointer = hashMap.get(s.charAt(i)) + 1;
			}
			hashMap.put(s.charAt(i), i);
		}
		return Math.max(s.length() - pointer, length);
	}
}

 

Java for LeetCode 003 Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4451855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!