c++ 5 line solution


  • 1
    X
    class Solution {
    public:
        int firstUniqChar(string s) {
          int table[26] = {0};
          for (auto c: s) table[c - 'a']++;
          for (int i = 0; i < s.length(); i++)
            if (table[s[i] - 'a'] == 1) return i;
          return -1;
        }
    };
    

  • 0
    A

    This solution is invalid. table is only size 26 but i could be > 26 since s.length() could be > 26. This can cause memory out of bounds corruption.

    for (int i = 0; i < s.length(); i++)
    if (table[i] - 'a' == 1) return i;

    I think you meant:

    for (int i = 0; i < s.length(); i++)
    if (table[s[i] - 'a'] == 1) return i;


  • 0
    X

    @Alan33D Yes, you are right, thank you for pointing out that. Do not know how this solution passed the test.


  • 0
    Y

    @xiaohui5319
    The solution passed because only a~z are used in the test.
    But you shouldn't assume only a~z will be used. There might be something else in the real case.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.