The first character that appears only once-Java

The first character that appears only once

Title description

Find the first character that appears only once in a string (0<=string length<=10000, all composed of letters), and return its position, if not, return -1 (case sensitive). (Counting from 0)

enter

"google"

return value

4

The first time I think of a violent solution, I traverse the number of occurrences all over again. But the complexity will be high. After doing it myself and thinking about it, I didn't really understand the solution after reading it. I got stuck in arr['character'], and then I went to Idea to go through it. Then there is perfect! Although I can’t figure it out, I can’t figure it out after reading the solution...Is this how my girlfriend often says that I’m self-confident?

Method (using HashCode cleverly)

if(str == null || str.length() == 0)
    return -1;
int[] ints = new int[123];
for(int i = 0;i<str.length();i++){
    
    
    // 这里很重要ints[字符]的写法,很巧妙地利用了字符会自动转换为int(经过hashcode)
    // 大家可以试一试ints['g']++这种写法是可以的,g会转成103
    ints[str.charAt(i)]++;
}
for (int i = 0; i < str.length(); i++) {
    
    
    if(ints[str.charAt(i)] == 1)
        return i;
}
return -1;
}

test

String c = "google";
int i = firstNotRepeatingChar(c);
System.out.println(i);

Output

4

Finally, a is the number 97, b is 98, and in turn, z is 122, so the array size is 123.

Guess you like

Origin blog.csdn.net/weixin_43957211/article/details/114883535