美文网首页
Longest Substring Without Repeat

Longest Substring Without Repeat

作者: 瞬铭 | 来源:发表于2018-07-31 13:54 被阅读0次

Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

PHP:i,j指针分别遍历数组,通过存储i到j的字符串,查找重复

 function lengthOfLongestSubstring($strInput){

     if(!$strInput){
         return 0;
     }

     $arrInput = str_split($strInput);
 
     $arrTmp = [];
     $maxLength = 0;
     for($i = 0; $i < count($arrInput); $i++){
         for($j = $i ; $j < count($arrInput); $j++){

             if(in_array($arrInput[$j] , $arrTmp)){ //j 指针找到重复的字符
                 $maxLength = count($arrTmp) >= $maxLength ? count($arrTmp) : $maxLength;
                 break;
             }

             $arrTmp[] = $arrInput[$j];
         }

         //j 指针轮询到最后一个,已经轮询到最后一个了,不用再i++了
         if($j == count($arrInput)){
             //echo "i:" . $i . "\t" . $arrInput[$i] . "\n";
             //echo "j:" . $j . "\t" . $arrInput[$j] . "\n";
             return ($j - $i) > $maxLength ? ($j - $i) : $maxLength;
         }

         $arrTmp = [];
     }
     return $maxLength;
 }

 //$str = "abcadfasdfqwesades";
 $str = "bbbbbbb";
 $max = lengthOfLongestSubstring($str);
 var_dump($max);exit;

java

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.isEmpty()){
            return 0;
        }
        String[] arr = s.split("");
        int maxLength = 0;
        int i,j = 0;
        
        HashMap<String,Integer> hash = new HashMap<String,Integer>();
        
        for(i = 0; i < arr.length ; i++){
            for(j = i; j < arr.length ; j++){
                if(hash.containsKey(arr[j])){
                    maxLength = hash.size() > maxLength ? hash.size() : maxLength;
                    break;
                }
                
                hash.put(arr[j], 1);
            }
            if(j == arr.length){
                
                  return (j - i) > maxLength ? (j - i) : maxLength;
            }
            hash.clear();

        }
        return maxLength;
    }
}

相关文章

网友评论

      本文标题:Longest Substring Without Repeat

      本文链接:https://www.haomeiwen.com/subject/pmxhvftx.html