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;
            
        }
    }
  • 相关阅读:
    Shell中的特殊变量和结构
    自由的Debian
    关于系统定制的一些链接
    超出两行显示省略号
    json转换
    区分LocalStorage和偏好数据
    去除谷歌浏览器中的默认文本框样式
    js访问xml
    js执行跨域请求
    mvc通过controller创建交互接口
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3552081.html
Copyright © 2011-2022 走看看