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.

题意:给一个字符串,找出没有重复的最长子串,求出元素个数。

思路:在左侧设置两个指针i,j,j不断向右移动。将j指针指到的元素判断,如果不在map中,则加入map。否则统计map中的元素个数,为当前子串的不同元素个数,然后将map中从i开始到与当前j指针发生冲突的元素位置位置的元素全部删除,然后把i指针指向当前冲突元素的右侧。

实现:

public class Solution {
     public int lengthOfLongestSubstring(String s ) {
           int max =0;
        Map<Character,Integer> map= new HashMap<Character,Integer>();
        char[]arr =s .toCharArray();
        for(int i =0,j =0;j <s .length();j++){//设置两个指针,从左向右遍历
           if(map .containsKey(arr[j])){//如果当前元素在map中,则表示有冲突。如果把当前元素加入子串也不会增加最大不同元素数,所以统计当前的元素数
               if(map .size()>max)
                    max= map.size();
               int index =map .get(arr [j ]);//找到map中造成冲突的元素
               for(int x =i ;x <=index ;x ++){//从左侧的指针开始到index为止的元素从map中删除
                    map.remove( arr[ x]);
              }
               map.put( arr[ j], j); //把当前元素加入map中
               i= index+1; //左侧指针指导index的右侧
          } else{//如果不在map中,则将当前元素加入map中
               map.put( arr[ j], j);
          }
        }
        return max >map .size()?max :map .size();//返回历史最大值与当前map元素中较大的值
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值