原来已经十几天没有更新了,真是一时拖延一时爽,一直拖延一直爽
387字符串中的第一个唯一字符
第一反应就是构建哈希表,一次遍历构建map,另一次遍历找出次数为1的返回
时间复杂度是O(N),空间复杂度是可能出现的字符种类个数,在这里就是26
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<int,int> count;
for(int i = 0; i < s.length(); i++){
count[s[i]] ++;
}
for(int i = 0; i < s.length(); i++){
if(count[s[i]] == 1) return i;
}
return -1;
}
};
看了题解说直接用数组计数会快很多,应该是建立哈希表比较复杂
class Solution {
public:
int firstUniqChar(string s) {
vector<int> count(27);
for(int i = 0; i < s.length(); i++){
count[s[i] - 'a'] ++;
}
for(int i = 0; i < s.length(); i++){
if(count[s[i] - 'a'] == 1) return i;
}
return -1;
}
};
389找不同
第一想法还是和上面一样,构建哈希数组进行计数
时间复杂度O(N),空间复杂度也和上面的一样
class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> count(27);
char res;
for(int i = 0; i < t.length(); i++){
count[t[i] - 'a'] ++;
}
for(int i = 0; i < s.length(); i++){
count[s[i] - 'a'] --;
}
for(int i = 0; i < t.length(); i++){
if(count[t[i] - 'a'] == 1) res = t[i];
}
return res;
}
};
看了题解之后不得不感慨大家太强了,不需要用哈希表,直接把两个字符串的字符的ascll码相加,两个对应减一下就可以了!这样空间复杂度为O(1)
class Solution {
public:
char findTheDifference(string s, string t) {
int sumt = 0;
int sums = 0;
for(int i = 0; i < t.length(); i++){
sumt += t[i];
}
for(int i = 0; i < s.length(); i++){
sums += s[i];
}
return sumt - sums;
}
};
还有一种位运算,把两个字符串中的所有字符全部进行异或运算,出现偶数次的那个字符就是要求的,异或运算完的结果就是答案
class Solution {
public:
char findTheDifference(string s, string t) {
int res = 0;
for(char c : t){
res ^= c;
}
for(char c : s){
res ^= c;
}
return res;
}
};