Is this code optimal? It is one pass and minimal second pass


  • 0
    2
    class Solution {
    public:
        struct Node {
            int count; 
            int index;
        };
        int firstUniqChar(string s) {
          map<char, int> m;
          vector<Node> v;
          for(int i=0; i<s.length(); i++) {
              if(m.count(s[i])) {
                  int index=m[s[i]];
                  v[index].count++;
              } else {
                  Node node;
                  node.index=i;
                  node.count=1;
                  v.push_back(node);
                  m[s[i]]=v.size()-1;
              }
          }
          for(int i=0; i<v.size(); i++) {
              if(v[i].count==1)
                return v[i].index;
          }
          return -1;
        }
    };
    

Log in to reply
 

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