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;
            
        }
    }
  • 相关阅读:
    根据数组对象中的某个属性值排序
    vue小知识
    vue项目中config文件中的 index.js 配置
    小问题
    原生无缝轮播
    webpack打包提交代码
    echarts
    面试问题
    MySql
    vue-router 跳转原理
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3552081.html
Copyright © 2011-2022 走看看