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

    从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            int[] count = new int[26];
      
            resetCount(count);
            
            int sLength = s.length();
            int maxL = 0;
            int start = 0;
            for(int i = 0; i < sLength; i++){
                int index = s.charAt(i) - 97;
                
                if(count[index] >= 0){
                    if(i - start > maxL){
                        maxL = i - start;
                    }
                    // need to backtrack !!!
                    i = count[index];
                    start = i + 1;
                    resetCount(count);
                    continue;
                }
                
                count[index] = i;
                
            }
            
            // if last round have no repeating characters, we should check
            if(maxL < sLength - start){
                maxL = sLength - start;
            }
            return maxL;
        }
        
        public void resetCount(int[] count){
            for(int i = 0; i < 26; i ++){
                count[i] = -1;   
            }
        }
    }
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s == null)
                return 0;
                
            char[] myChar = s.toCharArray();
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            int maxLen = 0;
            for(int i = 0 ; i < myChar.length; i++){
                if(map.containsKey(myChar[i])){
                    maxLen = map.size() > maxLen ? map.size() : maxLen;
                    i = map.get(myChar[i]);
                    map.clear();
                }else{
                    map.put(myChar[i], i);
                }
            }
            maxLen = map.size() > maxLen ? map.size() : maxLen;
            return maxLen;
            
        }
    }
  • 相关阅读:
    day7 反射
    day7 面向对象进阶
    day7 面向对象class()学习
    day6 subprocess模块、logging模块
    day6 hashlib模块
    day6 ConfigParser模块 yaml模块
    day6 xml文件格式的处理
    day6 shelve模块
    day6 SYS模块
    Servlet的学习之Response响应对象(1)
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3552081.html
Copyright © 2011-2022 走看看