389.找不同
题目
给定两个字符串 s
和 t
,它们只包含小写字母。
字符串 t
由字符串 s
随机重排,然后在随机位置添加一个字母。
请找出在 t
中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde" 输出:"e" 解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y" 输出:"y"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s
和t
只包含小写字母
方法一:
class Solution {
public:
char findTheDifference(string s, string t) {
char p = ' ', q = ' ';
int k;
if (s == "") {
p = t[0];
return p;
} else {
string::iterator j;
string::iterator i;
for (j = t.begin(); p == q; t.erase(0, 1)) {
p = *j;
i = s.begin();
q = *i;
while (p != q && i != s.end()) {
i++;
q = *i;
}
*i = s[k];
s.erase(k, 1);
};
return p;
}
}
};
总结:
string类:length、erase等函数的使用。
迭代器。
注意循环的判断。改进if break。
赋值语序。
方法二:
class Solution {
public:
char findTheDifference(string s, string t) {
int count[26], result;
for (int k = 0; k <= 26; k++) {
count[0] = 0;
}
for (int i = 0; i < s.length(); i++) {
count[int(s[i]) - 97]++;
}
for (int j = 0; j < t.length(); j++) {
count[int(t[j]) - 97]--;
}
for (int n = 0; n <= 26; n++) {
if (count[n] != 0) {
result = char(n + 97);
break;
}
}
return result;
}
};
总结:
ASCLL值及转换。
return不要写在if内。