LeetCode 3 Longest Substring Without Repeating Characters
来源:互联网 发布:淘宝助理没有安能物流 编辑:程序博客网 时间:2024/05/20 05:55
Longest Substring Without Repeating Characters
Total Accepted: 62866 Total Submissions: 299055My SubmissionsGiven 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
- LeetCode 3 - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- LeetCode(3) Longest Substring Without Repeating Characters
- leetcode 3LONGEST SUBSTRING WITHOUT REPEATING CHARACTERS
- Leetcode【3】:Longest Substring Without Repeating Characters
- [leetcode 3] Longest Substring Without Repeating Characters
- [Leetcode] 3 - Longest Substring Without Repeating Characters
- LeetCode 3:《Longest Substring Without Repeating Characters》
- [leetcode 3] Longest Substring Without Repeating Characters
- [leetcode] 3 Longest Substring Without Repeating Characters
- [Leetcode]3Longest Substring Without Repeating Characters
- leetcode 3 Longest Substring Without Repeating Characters
- LeetCode #3 Longest Substring Without Repeating Characters
- leetcode-3 Longest Substring Without Repeating Characters
- LeetCode 3 Longest Substring Without Repeating Characters
- leetcode 3: Longest Substring Without Repeating Characters
- LeetCode 3 Longest Substring Without Repeating Characters
- 第九周阅读程序二:字符串类的设计
- leetcode--Substring with Concatenation of All Words
- oracle中job的执行时间
- 保存gif文件.m
- 三维骨架化
- LeetCode 3 Longest Substring Without Repeating Characters
- Objective-C开发编码规范
- 第9周-窗口程序-小型计算器
- HBase简单介绍
- 线程同步的方式和机制
- eclipse 之中出现了 Resource leak: 'in' is never closed
- hihocoder#1054 : 滑动解锁
- 链表实现的粗略的通讯录
- Log4j配置