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中,字符为键,下表索引为值

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

  • 相关阅读:
    iOS 面向对象
    iOS 构建动态库
    iOS 单例
    iOS 操作系统架构
    iOS 编译过程原理(1)
    Category
    CoreText
    dyld
    block
    (CoreText框架)NSAttributedString 2
  • 原文地址:https://www.cnblogs.com/lianliang/p/5328017.html
Copyright © 2011-2022 走看看