zoukankan      html  css  js  c++  java
  • 3.无重复字符的最长子串

     1 //方法一:使用HashMap记录字符的位置,实现滑动窗口
     2     public int lengthOfLonggestSubstring(String s) {
     3         if(s == null) {
     4             throw new IllegalArgumentException();
     5         }else {
     6             Map<Character, Integer> map = new HashMap<>();
     7             char ch = ' ';
     8             int maxLen = 0;
     9             int subIndex =0;
    10             for(int i=0; i < s.length(); i++) {
    11                 ch = s.charAt(i);
    12                 if(!map.containsKey(ch)) {
    13                     map.put(ch, i);
    14                     maxLen = Math.max(maxLen, i - subIndex + 1);
    15                 }else {
    16                     //若出现重复字符,判断重复字符索引是否大于当前开始索引,若是,则将左侧开始索引更改为重复字符后一位
    17                     subIndex = Math.max(map.get(ch) + 1, subIndex);
    18                     //更改重复字符索引为新的位置
    19                     map.put(ch, i);
    20                     //如果重复字符索引小于当前开始索引,字符串长度会加1,否则得到的结果比实际值小1
    21                     maxLen = Math.max(maxLen, i - subIndex + 1);
    22                 }
    23             }
    24             return maxLen;
    25         }
    26  }
     1 // 该方法利用HashSet,使用滑动窗口的模式
     2    public int lengthOfLonggestSubstring(String s) {
     3         if(s == null) {
     4             throw new IllegalArgumentException();
     5         }else if(s.equals("")) {
     6             return 0;
     7         }else {
     8             Set<Character> set = new HashSet<>();
     9             int i=0;
    10             int j=0;
    11             int len = s.length();
    12             int maxLen = 0;
    13             while(i < len && j < len) {
    14                 if(!set.contains(s.charAt(j))) {
    15                     set.add(s.charAt(j));
    16                     j++;
    17                     maxLen = Math.max(maxLen, j-i);
    18                 }else {
    19                     //可以确定出现重复字符后的重新开始的位置,比如abcbad,出现重复的b后,会删除最开始的ab,
    20                     //从c开始
    21                     set.remove(s.charAt(i));
    22                     i++;
    23                 }
    24             }
    25             return maxLen;
    26         }    
    27     }
    无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧
  • 相关阅读:
    【数据结构与算法】用go语言实现数组结构及其操作
    ElasticSearch搜索引擎
    【系统】Libevent库和Libev
    pod管理调度约束、与健康状态检查
    使用yaml配置文件管理资源
    Oracle中exists替代in语句
    【oracle】通过存储过程名查看package名
    解决Flink消费Kafka信息,结果存储在Mysql的重复消费问题
    利用Flink消费Kafka数据保证全局有序
    Oracle 字符集的查看和修改
  • 原文地址:https://www.cnblogs.com/xiyangchen/p/10804681.html
Copyright © 2011-2022 走看看