1. 程式人生 > >[LeetCode] First Unique Character in a String 尋找第一個不重複出現的字元

[LeetCode] First Unique Character in a String 尋找第一個不重複出現的字元

        思路:尋找字串中的第一個不重複出現的字元,一種判斷的思路是:某個字元的首次出現位置與最後出現位置相同,則可判斷該字元在字串中不重複。呼叫標頭檔案<string>中的兩個函式 find_first_of() 和 find_last_of() ,各自返回值為首次出現位置和末次出現位置,當兩個返回值相等是,得到不重複出現的字元。

        程式碼如下:

#include<iostream>
#include<string.h>
using namespace std;

class Solution {
public:
    int firstUniqChar(string s) {
        for(int i = 0 ; i < s.size() ; i ++)
        {
        //	cout << "first :" << s.find_first_of(s[i]) << endl;
        //	cout << "last : "<< s.find_last_of(s[i]) << endl; 
            if(s.find_first_of(s[i]) == s.find_last_of(s[i]))
                return i;
        }
        return -1;
    }
};

int main()
{
	Solution text;
	cout << text.firstUniqChar("leetcode") << endl; 
	cout << text.firstUniqChar("loveleetcode") << endl;
	return 0;
}