LeetCode刷题笔录 Longest Substring Without Repeating Characters

50 篇文章 0 订阅
26 篇文章 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.


这题似曾相识,似乎是数据结构课做过的题,不过忘得一干二净。。。。

一开始傻呵呵的用了暴力方法,慢的要死;看到提示了知道可以用一个table来存储每一个字符在字符串中的位置。其实这是一个对于字符串问题的通用方法,因为字符本质上就是一个Unique的数字,因此建立一个数组,数组的下标表示这个字符的ASCII码,元素表示其在字符串中的位置即可。另外一个逻辑就是当遇到和之前重复的字符(前一次出现称为Occur 1, 这一次出现称为Occur 2)时,即遇到了一个可能的最大值;进行比较后,将下一次扫描的起点设置为刚才这个重复字符的Occur 1的后一位即可。看到一张图,觉得很不错,转载过来:



代码如下:

public int lengthOfLongestSubstring(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
		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 char
			if (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;
	}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值