Leetcode 387. First Unique Character in a String

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 387. First Unique Character in a String_第1张图片
First Unique Character in a String

2. Solution

  • Two loops
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
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;
    }
};

Reference

  1. https://leetcode.com/problems/first-unique-character-in-a-string/description/

你可能感兴趣的:(Leetcode 387. First Unique Character in a String)