[LeetCode] 3. Longest Substring Without Repeating Characters

19 篇文章 0 订阅
9 篇文章 0 订阅

原题链接: https://leetcode.com/problems/longest-substring-without-repeating-characters/

1. 题目介绍

Given a string, find the length of the longest substring without repeating characters.

给出1个字符串,寻找没有重复字母的最长子串。

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
Note that the answer must be a substring, 
"pwke" is a subsequence and not a substring.
必须是“子串”,而不是“子序列”

2. 解题思路

2.1 方法1:暴力搜索

使用 i 、j 两个变量,考虑所有可能的子串,使用集合存储子串中出现的字母个数。如果遇到重复出现的字母,则去考虑下一个子串,并取每个无重复字母的子串的最大长度。
时间复杂度O(n2)
实现代码

class Solution {
	    public int lengthOfLongestSubstring(String s) {
	        int length = s.length();
	        if(length == 0) {
	        	return 0;
	        }
	        HashSet<Character> set = new HashSet<>();
	        
	        int Count = 1;
	        for(int i = 0 ; i<length ; i++) {
	        	set.clear();
	        	int subMax = 1;
	        	set.add(s.charAt(i));
	        	
	        	for(int j = i+1 ; j<length ; j++) {
	        		if( set.contains(s.charAt(j)) == true ) {
	        			break;
	        		}else {
	        			subMax++;
	        			set.add(s.charAt(j));
	        		}
	        	}
	        	Count = Math.max(Count, subMax);
	        }
	        return Count;
	    }
	}

注:以下内容的思路和代码来自 https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/

2.2 方法2:滑动窗口法(双指针法)

滑动窗口是数组 / 字符串问题中常用的抽象概念。 窗口是指是在数组 / 字符串中由开始和结束下标中间的所有元素的集合,即 [ i , j ) (左闭,右开)。而滑动窗口是可以将两个边界向某一方向“滑动”的窗口。

例如,我们将 [ i , j ) 向右滑动 1 个元素,则它将变为 [ i+1 , j+1 )(左闭,右开)。

我个人认为滑动窗口法是双指针法的一种变形,可以归到双指针法里面去。

在本题中,我们将当前窗口 [ left , right ) (最初 left = right)中的所有元素存储在 HashSet 中。 然后我们向右侧滑动索引 right,如果第 right 个元素它不在 HashSet集合 中,说明这个字符之前没有被用过,于是我们将其放入集合,然后继续滑动 right 。当遇到 s[ right ] 已经存在于 HashSet 中时,说明s[ right ]和窗口 [ left , right ) 中的某个字符重复了。这时我们就要停止向右扩展窗口了,而应该将窗口从左边收缩。收缩窗口到什么时候为止呢?直到窗口排除了那个和s[ right ]重复的字符时,结束收缩。

我们找到的没有重复字符的子字符串将会以索引 left 开头,right - 1结尾。每找到这样一个子字符串时,就要把长度记下来,和已经记录的Count值比较,如果比Count大,那么就要更新Count的值。

时间复杂度:O(2n) = O(n),在最糟糕的情况下,每个字符将被 i 和 j 访问两次。比如 “aaaa” 就是一种最糟糕的情况,窗口的大小始终在0和1之间交替。

空间复杂度:O( min(m, n) ) 。滑动窗口法需要 O(k) 的空间,其中 k 表示 Set 的大小。而 Set 的大小取决于字符串 n 的大小以及字符集/字母 m 的大小。

实现代码

class Solution {
    public int lengthOfLongestSubstring(String s) {
		int length = s.length();
		if(length == 0) {
			return 0;
		}
		
		int left = 0;
		int right = 0;
		HashSet<Character> set = new HashSet();
		int Count = 0;
		
		while(left <length && right<length) {
			//如果right所指的字符没有在集合里,则继续向右扩展窗口
			//并记录此时的数组长度,如果超过Count,则更新Count
			if( set.contains(s.charAt(right) ) == false) {
				set. add(s.charAt(right));
				right ++;
				Count = Math.max(Count,right - left );
			}
			//如果right所指的字符在集合里,则停止向右扩展,从左边收缩窗口
			else {
				set.remove(s.charAt(left));
				left ++;
			}
		}
		return Count;
	}
}

2.3 方法3:优化滑动窗口法:不必逐个增加left

上述的方法最多需要执行 2n 个步骤。事实上,它可以被进一步优化为仅需要 n 个步骤。上面的方法中,如果遇到重复的字符,我们需要逐渐增加 left 。这次我们使用 HashMap 存储每个字符的位置,于是遇到重复的字符时,我们可以让 left 直接跳到窗口内部和 right 重复的字符的后面,不用再1个1个地增加。

时间复杂度:O(n),索引 right 将会迭代 n 次。

空间复杂度:O( min(m, n) ) 。滑动窗口法需要 O(k) 的空间,其中 k 表示 Set 的大小。而 Set 的大小取决于字符串 n 的大小以及字符集/字母 m 的大小。

实现代码

class Solution {
    public int lengthOfLongestSubstring(String s) {
		int length = s.length();
		if(length == 0) {
			return 0;
		}
		
		int left = 0;
		int right = 0;
		HashMap<Character,Integer> map = new HashMap();
		int Count = 0;
		
		while( right <length ) {
			//如果right所指的字符没有在集合里,则将其放入集合
			if( map.containsKey(s.charAt(right) ) == false ){
				map.put(s.charAt(right), right );
			}
			//如果right所指的字符在集合里,则停止向右扩展,从左边收缩窗口
			//收缩时left会直接跳到窗口内部和right重复的字符的后面
			//当然,不能比原来的left小,
			//比如"tmmzuxt",当left指向2(m),right指向6(t)时,left不能再跳到1(t)去
			else {
				left = Math.max(map.get(s.charAt(right)) + 1, left);
				map.put(s.charAt(right), right );
			}
			Count = Math.max(Count, right - left +1);
			right ++;
		}
		
		return Count;
	}
}

把上面的代码精简一下:

实现代码

class Solution {
    public int lengthOfLongestSubstring(String s) {
		int length = s.length();
		if(length == 0) {
			return 0;
		}
		
		int left = 0;
		int right = 0;
		HashMap<Character,Integer> map = new HashMap();
		int Count = 0;
		
		while( right <length ) {
			//如果right所指的字符没有在集合里,则将其放入集合
			if( map.containsKey(s.charAt(right) )  ){
				left = Math.max(map.get(s.charAt(right)) + 1, left);
				map.put(s.charAt(right), right );
			}
			map.put(s.charAt(right), right );
			Count = Math.max(Count, right - left +1);
			right ++;
		}
		return Count;
	}
}

2.4 方法4:优化滑动窗口法:数组替换 HashMap

这是对滑动窗口法的第3次优化。
当字符集比较小的时侯,我们可以用一个整数数组作为直接访问表来替换 HashMap。
数组的下标是int类型,但是如果将同样的数看作char类型,那就是ASCII码表中的字符了。
比如:

int a = 65;
System.out.println( (char)a);

输出结果将会是

A

常用的替换方式如下所示:

int [26] 用于字母 ‘a’ - ‘z’或 ‘A’ - ‘Z’
int [128] 用于ASCII码
int [256] 用于扩展ASCII码

用数组替代 HashMap。数组下标代表字符,数组中的值存放某个字符的位置的后面一位的下标。在这个思路下,左下标的移动公式是:

left = Math.max( index[s.charAt(right)], left);

数组的元素的初始值都是0,所以如果遇到没有重复的字符,就是在0和left本身中取一个最大的作为新的left;如果是重复过的字符,那么就可以直接跳到重复字符的后一位。

时间复杂度: O(n) ,索引 right 将会迭代 n 次。
空间复杂度: O(m) ,m 是字符集的大小。

实现代码

class Solution {
   public int lengthOfLongestSubstring(String s) {
		int length = s.length();
		if(length == 0) {
			return 0;
		}
		
		int left = 0;
		int right = 0;
		int [] index = new int[128]; 
		int Count = 0;
		
		while( right <length ) {
			//左下标在重复的字符下一位和左下标自身之间选一个较靠后的
			left = Math.max( index[s.charAt(right)], left);
	        //没有重复的子串中,取最大的长度
	        Count = Math.max( Count, right - left +1);
	        //存储right字符后面一位的下标
	    	index[ s.charAt(right) ] = right + 1;
				
			right++;
		}		
		return Count;
	}
}

3. 相似题目

395. Longest Substring with At Least K Repeating Characters
找出每个字母都至少重复k次的最长子串

4. 参考资料

https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值