【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters
生活随笔
收集整理的这篇文章主要介绍了
【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
题目
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.这道题看似简单,但是用遍历方法的话非常麻烦。下面这种用hashmap处理方法,是在discuss里看到的,很巧妙。
代码
public class Solution {public int lengthOfLongestSubstring(String s) {if(s.length()==0) return 0;HashMap<Character,Integer> map=new HashMap<Character,Integer>();int max=0;for(int i=0,j=0;i<s.length();i++){if(map.containsKey(s.charAt(i))){j = Math.max(j,map.get(s.charAt(i))+1);}map.put(s.charAt(i),i);max = Math.max(max,i-j+1);}return max;}}代码下载:https://github.com/jimenbian/GarvinLeetCode
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/
总结
以上是生活随笔为你收集整理的【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【LeetCode从零单排】No 114
- 下一篇: 【LeetCode从零单排】No15 3