Find the first un-repeated character in a string

后端 未结 30 1300
猫巷女王i
猫巷女王i 2020-11-27 18:29

What is the quickest way to find the first character which only appears once in a string?

30条回答
  •  难免孤独
    2020-11-27 19:18

    in C, this is almost Shlemiel the Painter's Algorithm (not quite O(n!) but more than 0(n2)).

    But will outperform "better" algorithms for reasonably sized strings because O is so small. This can also easily tell you the location of the first non-repeating string.

    char FirstNonRepeatedChar(char * psz)
    {
       for (int ii = 0; psz[ii] != 0; ++ii)
       {
          for (int jj = ii+1; ; ++jj)
          {
             // if we hit the end of string, then we found a non-repeat character.
             //
             if (psz[jj] == 0)
                return psz[ii]; // this character doesn't repeat
    
             // if we found a repeat character, we can stop looking.
             //
             if (psz[ii] == psz[jj])
                break; 
          }
       }
    
       return 0; // there were no non-repeating characters.
    }
    

    edit: this code is assuming you don't mean consecutive repeating characters.

提交回复
热议问题