[LeetCode] Longest Substring Without Repeating Characters
来源:互联网 发布:window7怎么连接网络 编辑:程序博客网 时间:2024/06/05 06:31
题目:
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.
思路:
暴力做法是找到s的每一个子串,再对子串进行重复字符检测,但是肯定不会通过LeetCode OJ的测试。基本思路还是循环,但是在遍历和判断是否有重复字符的时候,选择用空间换时间的策略,引入两个数组exist[]和position[],分别存储的信息是该字符是否出现在当前子串中以及出现的下标。需要注意的是字符集不仅仅是{a,b,c……,z},可能包括特殊字符,这里考虑的是ASCII字符集。
代码
public class Solution { public int lengthOfLongestSubstring(String s) { int start = 0,maxLen = 0; int[] position = new int[255]; boolean[] exist = new boolean[255]; if(s == null || s.equals("")) return 0; for(int i = 0;i < 255;i++){ position[i] = -1; exist[i] = false; } for(int i = 0;i < s.length();i++){ if(!exist[s.charAt(i) - ' ']){ position[s.charAt(i) - ' '] = i; exist[s.charAt(i) - ' '] = true; maxLen = ((i - start) + 1 > maxLen) ? (i - start) + 1 : maxLen; } else{ for(int j = start;j < i;j++){ exist[s.charAt(j) - ' '] = false; } start = position[s.charAt(i) - ' '] + 1; exist[s.charAt(start) - ' '] = true; position[s.charAt(start) - ' '] = start; i = start; } } return maxLen; }}
0 0
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- leetcode之Longest Substring Without Repeating Characters
- js返回上一页并刷新代码整理
- [OpenJudge-NOI]不定方程求解 扩展欧几里德
- 分组转换时延的计算
- 1005. Spell It Right (20)
- [OpenJudge-NOI]乘积最大的拆分
- [LeetCode] Longest Substring Without Repeating Characters
- 鼎智收购北斗星手机网 推全新手机品牌青葱
- [OpenJudge-NOI]连乘积末尾0的个数
- 1006. Sign In and Sign Out (25)
- eclipse不能写入classpath
- [OpenJudge-NOI]质数的和与积
- POJ——3253 Fence Repair(优先队列)
- 1007. Maximum Subsequence Sum (25)
- javaWeb--API 自动化测试框架分享