Longest Substring Without Repeating Characters

题目描述:

Given a string, find the length of the longest substring without repeating characters.


Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be asubstring, "pwke" is a subsequence and not a substring.


这个题想了好久才做出来,不应该。这种题应该问一下考官这些字符的范围。


最简单的思路就是每一个字母都往前找和它相同的,记下来最大的值即可,这样的时间复杂度是n*n,肯定超时。

思路其实就是和动态规划差不多,每一个字母看前面的最长无重复字母子串长度为多少,然后看自己与上一次出现的位置之差是多少,比较两者最小值就得到这个字母最长无重复子串长度了。

比如:

addsa

当考虑最后一个a的最长无重复子串长度时,s的最长无重复子串长度为2,那么2+1=3,上一个a和这个a之间位置的差为4,取较小值为3,所以包含最后一个a的最长无重复子串长度为3

dsaba

当考虑最后一个a的最长无重复子串长度时,b的最长无重复子串长度为2,那么4+1=5,上一个a和这个a之间位置的差为2,取较小值为2,所以包含最后一个a的最长无重复子串长度为2

代码如下:

public int lengthOfLongestSubstring(String s) {
    if(s==null||s.length()==0)
    	return 0;
    if(s.length()==1)
    	return 1;
    Map
  
  
   
    positionMap=new HashMap
   
   
    
    ();
    Map
    
    
     
      numMap=new HashMap
     
     
      
      ();
    char[] chars=s.toCharArray();
    positionMap.put(chars[0], 0);
    numMap.put(chars[0], 1);
    int result=1;
    for(int i=1;i
      
      
        num?result:num; } return result; } 
      
     
     
    
    
   
   
  
  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值