LeetCode 3 Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

  Total Accepted: 62866  Total Submissions: 299055 My Submissions

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.

解题报告:

这个可以本来可以直接用暴力的方式来解决这个问题,但是要考虑到时间限制,想到了HashSet方法,HashSet中添加的字符不能有重复的,在发现重复时,

可以考虑清空HashSet,然后再继续添加字符。

代码:

public class Solution{
public int lengthOfLongestSubstring(String s) {
		if(s==null && s.length()==0)
	        return 0;
	    HashSet<Character> set = new HashSet<Character>();
	    int max = 0;
	    int walker = 0;
	    int runner = 0;
	    while(runner<s.length())
	    {
	        if(set.contains(s.charAt(runner)))
	        {
	            if(max<set.size())
	            {
	                max = set.size();
	            }
	            while(s.charAt(walker)!=s.charAt(runner))
	            {
	                set.remove(s.charAt(walker));
	               walker++;
	            }
	         walker++;
	        }
	        else
	        {
	            set.add(s.charAt(runner));
	        }
	        runner++;
	    }
	    max = Math.max(max,runner-walker);
	    return max;
	}
}
通过上面的问题,我们可以联想到最长公共子序列的求解方法,也是时间复杂度为O(n)

下面是最大子序列和的求解:

public int maxSubSum(int[] a) {
		int maxSum = 0;
		int thisSum = 0;
		for (int i = 0; i < a.length; i++) {
			thisSum += a[i];
			if (thisSum > maxSum)
				maxSum = thisSum;
			else if (thisSum < 0)
				thisSum = 0;
		}
		return maxSum;
	}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值