LeetCode 3 Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝助理没有安能物流 编辑:程序博客网 时间:2024/05/20 05:55

Longest Substring Without Repeating Characters

 Total Accepted: 62866 Total Submissions: 299055My 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