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;
            
        }
    }
  • 相关阅读:
    Azure的CentOS上安装LIS (Linux Integration Service)
    使用PowerShell在Azure China创建Data Warehouse
    通过php的MongoDB driver连接Azure的DocumentDB PaaS
    Azure RBAC管理ASM资源
    Azure基于角色的用户接入控制(RBAC)
    通过PowerShell命令给Azure VM添加CustomScriptExtension
    手把手教你创建Azure ARM Template
    MySQL数据表列转行
    MySQL
    MySQL游标使用
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3552081.html
Copyright © 2011-2022 走看看