Prove safety offer34: The first character appears only once in the position

1 Title Description

  In one string (0 <= length of the string <= 10000, all of the alphabet) find a first character appears only once, and returns to its position, or -1 if not (case-sensitive).

2 ideas and methods

 ch[str[i]]++;

if(ch[str[i]]==1)  return i;

3 C ++ core code

 1 class Solution {
 2 public:
 3     int FirstNotRepeatingChar(string str) {
 4         int len = str.length();
 5         if(len==0)
 6             return -1;
 7         char ch[256] = {0};
 8         for(int i=0;i<len;i++)
 9             ch[str[i]]++;
10         for(int i=0;i<len;i++)
11         {
12             if(ch[str[i]]==1)
13                 return i;
14         }
15         return -1;
16     }
17 };
View Code

Reference material

https://blog.csdn.net/u013686654/article/details/76125009

Guess you like

Origin www.cnblogs.com/wxwhnu/p/11421105.html