LeetCode_Longest Substring Without Repeating Characters

本文介绍了一种算法,用于解决寻找给定字符串中最长无重复字符子串的问题。通过使用双指针技巧和哈希集合数据结构,实现了一个高效的时间复杂度解决方案。文章详细解释了解题思路,并提供了两种不同的代码实现方式,最后通过实例展示了算法的正确性和有效性。

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.


解题思路:两个指针,第一个指针遍历整个字符串,第二个指针并记录子串的起始位置。代码中,遍历指针即为for循环中的i,起始位置记录指针为startIndex。遍历过程中,发现有字母已经在之前的子串中出现过,则将开始指针移动至第一次出现的位置+1。并且计算当前的length,与之前记录的length比较,取大者。


Time Limit Exceeded

public class Solution {
    public int lengthOfLongestSubstring(String s) {
		if (s == null) {
			return 0;
		}

		List<String> charArr = new ArrayList<String>();

		int length = 0;
		int startIndex = 0;
		if (s.length() == 0) {
			return 0;
		}

		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			String key = String.valueOf(c);
			if (charArr.contains(key)) {
				int tmpLength = i - startIndex;
				int index = charArr.indexOf(key);
				startIndex = index + 1;

				length = length < tmpLength ? tmpLength : length;

				for (int j = 0; j < startIndex; j++) {
					charArr.add(j, "-");
				}
			}
			charArr.add(key);
		}
		int tmpLength = s.length() - startIndex;
		length = length < tmpLength ? tmpLength : length;
		return length;
	}
}

Accepted

public class Solution {
    public int lengthOfLongestSubstring(String s) {
		if (s == null) {
			return 0;
		}


		Map<String, Integer> charMap = new HashMap<String, Integer>();
		int length = 0;
		int startIndex = 0;
		if (s.length() == 0) {
			return 0;
		}


		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			String key = String.valueOf(c);
			if (charMap.containsKey(key)) {
				int tmpLength = i - startIndex; // 发现存在,则计算当前最大长度
				length = length < tmpLength ? tmpLength : length; // 取最大长度
				if (charMap.get(key) >= startIndex) {
					startIndex = charMap.get(key) + 1; // 开始位置记录为上一次出现的位置+1
				}
				charMap.put(key, i);
			} else {
				charMap.put(key, i);
			}
		}


		int tmpLength = s.length() - startIndex;
		length = length < tmpLength ? tmpLength : length;
		return length;
	}
}


膜拜解法:

public int lengthOfLongestSubstring1(String s) {
		int begin = 0, end = 0;
		int flag[] = new int[256];
		int max = 0;

		while (end < s.length()) {
			if (flag[s.charAt(end)] == 0) { // 未标记,说明未出现过
				flag[s.charAt(end)]++; // 标记之,已经出现
				end++; // 遍历下一个
				max = (end - begin) > max ? (end - begin) : max;
			} else {
				flag[s.charAt(begin)]--; // 已经遍历到此字母,清除
				begin++;
			}
		}
		return max;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值