The first occurrence of a character position only once the title description
The position of the first occurrence of a character in a string (1<= string length <=10000, all composed of letters) is found. If the string is empty, return-1. Position index starting from 0
Ideas
- Each character is compared to the time complexity O (N2), so we create a hash table to store each character corresponding occurrences, scan the number of times, scan the second time to find the first occurrence of a character, time complexity O (n)
- Sacrifice space for time, hash table lookup Time is O (1)
- Note: The case of a character that does not meet such a condition at last
Code
PublicClass Solution {PublicIntFirstnotrepeatingchar(String str) {if (str = = NULL | | str.length () = =0) {Return-1;}int[] Table =Newint[256]; char[]strchar = Str.tochararray (); for (int i = 0; i < table.length; I + +) {Table[i] = 0;} for (int i = 0; i < strChar.length ; i++) {table[(int) strchar[i]]++;} int position = 0; while (Position < strchar.length && table[(int) strchar[position]]! = 1) {position++;} if (position = strchar.length) {return- 1;} return position;}
The first occurrence of a character position-the sword is an offer