First Unique Character in a String

2019-05-25 22:57:07 浏览数 (1)

1. Description

2. Solution

  • Two loops
代码语言:javascript复制
class Solution {
public:
    int firstUniqChar(string s) {
        int index[256] = {0};
        for(int i = 0; i < s.size(); i  ) {
            index[s[i]]  ;
        }
        for(int i = 0; i < s.size(); i  ) {
            if(index[s[i]] == 1) {
                return i;
            }
        }
        return -1;
    }
};
  • Nested loop
代码语言:javascript复制
class Solution {
public:
    int firstUniqChar(string s) {
        int index[256] = {0};
        for(int i = 0; i < s.size(); i  ) {
            index[s[i]]  ;
            if(index[s[i]] != 1) {
                continue;
            }
            bool flag = false;
            for(int j = i   1; j < s.size(); j  ) {
                if(s[i] == s[j]) {
                    flag = true;
                    break;
                }
            }
            if(!flag) {
                return i;
            }
        }
        return -1;
    }
};

0 人点赞