1050 String Subtraction (20 分)
Given two strings S?1?? and S?2??, S=S?1???S?2?? is defined to be the remaining string after taking all the characters in S?2?? from S?1??. Your task is simply to calculate S?1???S?2?? for any given strings. However, it might not be that simple to do it fast.
Input Specification:
Each input file contains one test case. Each case consists of two lines which gives S?1?? and S?2??, respectively. The string lengths of both strings are no more than 10?4??. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.
Output Specification:
For each test case, print S?1???S?2?? in one line.
Sample Input:
They are students.
aeiou
Sample Output:
Thy r stdnts.
题目特意强调时间复杂度,所以我写的时候会稍微考虑一点运行效率。首先就是第二个字符串也就是减数字符串中的字符是存在重复的可能的,如果重复的字符也重复地去进行删除操作,那时间复杂度不可能好,所有我先对s2进行去重,简单地说就是先排序再选取字符,得到s2中字符的不重复集合,剩下的删除操作就比较常规了,就是用substr截取就行了。最后直接就通过了,想想应该是对时间的要求还不是很高,我这个代码应该还是有优化的空间的,anyway,通过了就行。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;bool compare(char a, char b)
{return a > b;
}
int main()
{string s1, s2;vector<char> arr,s2Arr;getline(cin,s1);getline(cin, s2);for (int i = 0; i < s2.length(); i++){arr.push_back(s2[i]);}sort(arr.begin(),arr.end(),compare);s2Arr.push_back(arr[0]);int index = 0;for (int i = 1; i < arr.size(); i++){if (s2Arr[index] != arr[i]){s2Arr.push_back(arr[i]);index++;}else if(s2Arr[index] == arr[i]){continue;}}for (int i = 0; i < s1.length(); i++){for (int j = 0; j < s2Arr.size(); j++){if (s1[i] == s2Arr[j]){s1 = s1.substr(0,i)+s1.substr(i+1, s1.size()-1-i);i--;break;}}}cout << s1;system("pause");return 0;
}
这里推荐一个博主的解法https://blog.csdn.net/sunbaigui/article/details/8656788
真的狠人