給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。如果不存在,則返回 -1。
這個時候題目沒有要求是多少時間複雜度,並且字符串中也只有小寫字母,暫時不考慮大寫字母;初步想法是兩次遍歷找到字符串中重複的字符;然後動態申請一個與字符串大小一樣的數組;將出現重複的位置標1;最後尋找數組中第一個0的位置就行;具體的代碼如下:
#include<iostream>
#include<string>
#include<memory>
using namespace std;
class Solution {
public:
int firstUniqChar(string s) {
int n = s.size(); char temp;
unique_ptr<int[]> num(new int[n]());//用unique_ptr去建立動態數組可以使用下標操作;在memory函數下;
if (n<1)
return -1;
if (n == 1)
return 0;
for (int i = 0; i<n - 1; i++)
{
temp = s[i];
for (int j = i + 1; j<n; j++)
{
if (temp == s[j])
{
num[i] = num[j] = 1;
break;
}
continue;
}
}
for (int i = 0; i<n; i++)
{
if (num[i] == 0)
return i;
}
return -1;
}
};
但是因爲這樣做的話時間複雜度爲o(n^2);並且沒有辦法處理複雜的環境,比如說有大寫字母的時候,所以想到應用ASCII碼去做,會很方便;第一步先定義一個長度爲256的0數組(其實125應該也夠了);第二步遍歷字符串,將每個字符串中的字符對應的ACSII碼位置標1,如果出現相同的,則在原有位置加1;第三步還是遍歷字符串,找到第一個字符對應的ASCII碼位置爲1的字符,返回其位置;這樣時間複雜度爲0(n),並且可以處理大寫字符;代碼如下:
#include <iostream> //利用ASCII碼錶;
using namespace std;
class Solution {
public:
int firstUniqChar(string s)
{
int p[256] = { 0 }; int n = s.size();
for (int i = 0; i < n; i++)
{
p[s[i]] += 1;
}
for (int j = 0; j < n; j++)
{
if (p[s[j]] == 1)
{
return j;
}
}
return -1;
}
};
int main()
{
Solution temp;
string s = "loveleetcode";
cout << temp.firstUniqChar(s) << endl;
system("pause");
return 0;
}