zoukankan      html  css  js  c++  java
  • [LeetCode]-algorithms-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.

    分析:求最大不重复子串的长度

    public int lengthOfLongestSubstring(String s) {
            char[] arr = s.toCharArray();
            HashMap<Character,Integer> map = new HashMap<Character,Integer>();
            int len = 0;
            for(int i=0; i<arr.length; i++){
                if(map.containsKey(arr[i])){
                    len = Math.max(len, map.size());
                    i = map.get(arr[i]);
                    map.clear();
                }else{
                    map.put(arr[i],i);
                }
            }
            len = Math.max(len, map.size());
            return len;
        }

    结语:依次把字符串的每个字符以及它对应的下表索引存入到Map中,字符为键,下表索引为值

    每插入一次,进行判断,如果存在则从这个重复的字符的下一个开始遍历

  • 相关阅读:
    set, unordered_set模板类
    C/C++ Bug记录
    win10远程连接
    C/C++缓冲区刷新问题
    hihocoder1711 评论框排版[并查集+set]
    makefile
    Virtual Table
    粤语
    xilinx SDK开发 GPIO使用API总结
    基于zynq 7020的串口UART中断实验
  • 原文地址:https://www.cnblogs.com/lianliang/p/5328017.html
Copyright © 2011-2022 走看看