原题
LintCode 702. Concatenated String with Uncommon Characters of Two Strings
Description
Two strings are given and you have to modify 1st string such that all the common characters of the 2nd strings have to be removed and the uncommon characters of the 2nd string have to be concatenated with uncommon characters of the 1st string.
Example
Given s1 = aacdb, s2 = gafd
return cbgf
Given s1 = abcs, s2 = cxzca;
return bsxz
解题
题意很清楚,就是将两个字符串中相同的去掉,不同的拼接。
首先创建一个字母表,用来保存有哪些字母是相同的。然后直接拼接两个字符串,然后删除其中在字母表中出现的重复字母即可。
代码
class Solution {
public:
/*
* @param : the 1st string
* @param : the 2nd string
* @return: uncommon characters of given strings
*/
string concatenetedString(string &s1, string &s2) {
// write your code here
bool alphabet[26] = {};
for (char i : s2) {
for (char j : s1) {
if (j == i) {
alphabet[j - 'a'] = true;
break;
}
}
}
string res = s1 + s2;
auto it = res.begin();
while (it != res.end()) {
if (alphabet[*it - 'a']) {
res.erase(it);
} else {
it++;
}
}
return res;
}
};
网友评论