LeetCode从零单排No 3 Longest Substring Without Repeating Characters

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
           
   }
    
}


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/



以上是关于LeetCode从零单排No 3 Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

python3 从零单排3_函数(购买商品小程序)

[CF从零单排#3] CF158A - Next Round

Python3 从零单排2_文件读写

Python3 从零单排_一些好玩的东西

Python3 从零单排28_线程队列&进程池&线程池

[leetcode-300-Longest Increasing Subsequence]