151 Reverse Words in a String
大致思路:整体反转后,对单词局部反转,最后消除多余空格。
class Solution {
public:
string reverseWords(string s) {
// 反转整个字符串
reverse(s.begin(), s.end());
int n = s.size();
int start = 0;
int end = 0;
while (end < n) {
// 寻找单词的末尾
while (end < n && s[end] != ' ') {
end++;
}
// 反转当前单词
reverse(s.begin() + start, s.begin() + end);
// 跳过空格,开始下一个单词
start = end + 1;
end++;
}
// 去除单词间多余的空格,并重建结果字符串【积累】
string result;
bool space = false;
for (char c : s) {
if (c != ' ') {
result += c;
space = true;
} else if (space) {
result += ' ';
space = false;
}
}
// 去除最后一个多余的空格, 【积累】
if (!result.empty() && result.back() == ' ') {
result.pop_back();
}
return result;
}
};
387 First Unique Character in a String
自己想的方法是做标记,t s中字符一致就标’0‘,过于麻烦 ,虽然通过了,时间快1min 。
【积累借助数组计字母出现次数】
class Solution {
public:
int firstUniqChar(string s) {
vector<int> count(26,0);
for(char c :s){
count[c-'a']++;
}
//遍历字符串,并判别该字符出现次数
for(int i = 0 ; i < s.size();i++){
int n = s[i] - 'a';
if(count[n] == 1){
return i;
}
}
return -1;
}
};
389 Find the Difference
该题也是,想到的就是做标记出现了就记’0’,最后判断不为’0’的那一字符就是多出来的。但很明显没有以下三种方法适合处理字符串。
方法一:借助数组对26字母计数,判断多余的字符
class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> count(26,0);
for(char c :s){
count[c-'a']++;
}
for(char x :t){
--count[x-'a'];
if(count[x-'a']<0){
return x;
}
}
return 0;
}
};
方法二:借助ascii码计算多余的字符
class Solution {
public:
char findTheDifference(string s, string t) {
int count = 0;
for(char c : t){
count+=c;
}
for(char c:s){
count-=c;
}
return count;
}
};
方法三:异或。
【积累】由于相同的字符两次异或会抵消,最终剩下的就是多出来的字符。
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;
}
};
383 Ransom Note
本题没有要求字符出现顺序一致,学习前两题思路,使用数组计数并判断。
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
//同前两题类似
vector<int> count(26,0);
for(char c :magazine){
count[c-'a']++;
}
for(char c :ransomNote){
count[c-'a']--;
}
for(int i = 0 ; i < count.size();i++){
if(count[i] < 0){
return false;
}
}
return true;
}
};