Find longest substring without repeating characters

前端 未结 30 2472
轻奢々
轻奢々 2020-12-12 18:07

Given a string S of length N find longest substring without repeating characters.

Example:

Input:

30条回答
  •  执念已碎
    2020-12-12 18:54

    Here is one more solution with only 2 string variables:

    public static String getLongestNonRepeatingString(String inputStr){
        if(inputStr == null){
            return null;
        }
    
        String maxStr = "";
        String tempStr = "";
        for(int i=0; i < inputStr.length(); i++){
            // 1. if tempStr contains new character, then change tempStr  
            if(tempStr.contains("" + inputStr.charAt(i))){
                tempStr = tempStr.substring(tempStr.lastIndexOf(inputStr.charAt(i)) + 1);
            }
            // 2. add new character
            tempStr = tempStr + inputStr.charAt(i);
            // 3. replace maxStr with tempStr if tempStr is longer
            if(maxStr.length() < tempStr.length()){
                maxStr = tempStr;
            }
        }
    
        return maxStr;
    }
    

提交回复
热议问题