星空网 > 软件开发 > Java

[LeetCode] 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。但是在算法的问题上就需要细致的思考了。

     有几个思考错误可能很多人会犯。比如说很多人第一个反应以为是求两个重复的数之间的length。就以下面这组数来做例子。

     1,2,3,4,5,6,2,7,8,3,9,0,8,7

     很多人第一个反应就是要算2和2之间,3和3之间,7和7之间,8和8之间的length。

     但是题目上并没有说这种without repeating的length,首尾的前一位后一位必须一样啊。这就是典型的误区了。光顾着找重复的了。

     这也是为什么在代码中,Math.max()method在if statement外面的原因。

     代码如下。

public class Solution {  public int lengthOfLongestSubstring(String s) {    if(s.length()<2){      return s.length();    }    HashMap<Character,Integer> map=new HashMap<Character,Integer>();    int len=s.length();    int end=1;    int start=0;    int max=1;    map.put(s.charAt(0),0);    while(end<len){      if(map.containsKey(s.charAt(end))&&map.get(s.charAt(end))>=start){        start=map.get(s.charAt(end))+1; //since it's for length,so need +1      }      max=Math.max(max,end+1-start); //also for length,end +1      map.put(s.charAt(end),end);      end++;    }    return max;  }}

 




原标题:[LeetCode] Longest Substring Without Repeating Characters

关键词:string

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

回款案例:成功帮客户追回巴基斯坦合作方拖欠的货款:https://www.kjdsnews.com/a/1480662.html
如何进行一场直播复盘分析?:https://www.kjdsnews.com/a/1480663.html
美国亚马逊的销售税和免税的州有哪些?:https://www.kjdsnews.com/a/1480664.html
游戏达到何种程度可以出海?:https://www.kjdsnews.com/a/1480665.html
深圳跨境电商卖家数量超15万;亚马逊PrimeDay或于7月举行:https://www.kjdsnews.com/a/1480666.html
如何轻松应对客户来访准备和商谈:https://www.kjdsnews.com/a/1480667.html
石象湖景区门票-石象湖景区门票优惠政策:https://www.vstour.cn/a/411243.html
北京到嵩山自驾游沿途景点 北京距离嵩山有多远:https://www.vstour.cn/a/411244.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流