PAT甲级真题 1084 Broken Keyboard (20分) C++实现(简单遍历搜索)

题目

On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters corresponding to those keys will not appear on screen.

Now given a string that you are supposed to type, and the string that you actually type out, please list those keys which are for sure worn out.

Input Specification:
Each input file contains one test case. For each case, the 1st line contains the original string, and the 2nd line contains the typed-out string. Each string contains no more than 80 characters which are either English letters [A-Z] (case insensitive), digital numbers [0-9], or _ (representing the space). It is guaranteed that both strings are non-empty.

Output Specification:
For each test case, print in one line the keys that are worn out, in the order of being detected. The English letters must be capitalized. Each worn out key must be printed once only. It is guaranteed that there is at least one worn out key.

Sample Input:

7_This_is_a_test
_hs_s_a_es

Sample Output:

7TI

思路

设置两个指针i、j分别指向s1、s2。

若对应字符相同则同时向右移动;
若字符不同且其大写没出现过,则将该字符的大写加入到s3中。

最后的s3即为所求。


柳神的方法是,在s2中查找s1中的每个字符,若某字符不存在且其大写在结果中未出现过,则将其大写加入结果中。代码如下:

#include 
#include 
using namespace std;
int main() {
    string s1, s2, ans;
    cin >> s1 >> s2;
    for (int i = 0; i < s1.length(); i++)
        if (s2.find(s1[i]) == string::npos && ans.find(toupper(s1[i])) == string::npos)
            ans += toupper(s1[i]);
    cout << ans;
    return 0;
}

代码十分简洁,只是复杂度稍微高点。

代码

#include 
#include 
using namespace std;
int main(){
    string s1, s2;
    cin >> s1 >> s2;
    string s3 = "";
    int i = 0;
    int j = 0;
    while (i<s1.size() && j<s2.size()){
        if (s1[i]==s2[j]){
            j++;
        }
        else if (s3.find(toupper(s1[i]))==string::npos){
            s3 += toupper(s1[i]);
        }
        i++;
    }
    while (i<s1.size()){
        if (s3.find(toupper(s1[i]))==string::npos){
            s3 += toupper(s1[i]);
        }
        i++;
    }
    cout << s3;
    return 0;
}

你可能感兴趣的:(PAT)