Detecting if a string has unique characters: comparing my solution to “Cracking the Coding Interview?”

后端 未结 7 1838
孤街浪徒
孤街浪徒 2020-12-22 16:43

I am working through the book \"Cracking the Coding Interview\" and I have come across questions here asking for answers, but I need help comparing my answer to the solution

7条回答
  •  自闭症患者
    2020-12-22 17:30

    This is the necessary correction to the book's code:

    public static boolean checkForUnique(String str){
        boolean containsUnique = false;
    
        for(char c : str.toCharArray()){
            if(str.indexOf(c) == str.lastIndexOf(c)){
                containsUnique = true;
            } else {
                return false;
            }
        }
    
        return containsUnique;
    }
    

提交回复
热议问题