P246

T1:

思路:利用set关联容器。将str2中的字符放入关联容器中,然后以此为参照物扫描str1的逐个字符,判断是否在str2中出现过,可用set中的find()函数。但是我的问题不在于这,而是在于处理带空格的字符串输入输出上。
输入输出参考文章 https://www.cnblogs.com/qiang-wei/p/9332201.html
利用getline(cin,string s)接受带空格的字符串。在输入字符串之前会输入一个标识字符串组数的n,接着输入回车标识输入n结束,下一步缓冲区中仍然存在着这个空行符,所以在输入字符串之前得清除缓冲区的换行符。用

cin.clear();
        cin.ignore();

清除缓冲区的一个字符,接着再用getline(cin,string s)输入字符串就正常了。

void deleteCharacter(string str1, string str2)
{
    if (str1.empty())
        return;
    if (str2.empty())
    {
        //cout << "str2 is empty" << endl;
        cout << str1 << endl;
        return;
    }
    set<char> strSet;
    int i = 0;
    while (str2[i]!='\0')
    {
        strSet.insert(str2[i]);
        ++i;
    }
    int j = 0;
    while (str1[j]!='\0')
    {
        if (strSet.find(str1[j]) == strSet.end())
        {
            cout << str1[j];
        }
        ++j;
    }
    cout << endl;

}

int main()
{
    int n;
    cin >> n;
    cin.clear();
    cin.ignore();
    while (n--)
    {
        string str1,str2;
        getline(cin, str1);
        getline(cin, str2);
        deleteCharacter(str1, str2);
    }
    return 0;
}

T2:

思路:同样运用set关联容器。由于set中insert特性,可以将字符串的字符insert进set容器中,若有重复的字符,则插入失败。

string deleteDuplicate(string str)
{
    string resultStr;
    if (str.empty())
        return resultStr;
    set<char> strSet;
    int i = 0;
    while (str[i]!='\0')
    {
        auto ret = strSet.insert(str[i]);
        if (ret.second)
        {
            resultStr.push_back(str[i]);
        }
        ++i;
    }
    resultStr.push_back('\0');
    return resultStr;
}

int main()
{
    int n;
    cin >> n;
    cin.clear();
    cin.ignore();
    while (n--)
    {        
        string str1;
        getline(cin, str1);
        string resultStr = deleteDuplicate(str1);
        cout << resultStr << endl;
    }
    return 0;
}

T3:

思路:用的书上的思想。注意hash数组的简历和初始化。

bool test(string str1, string str2)
{
    if (str1.length() != str2.length()||str1.empty()||str2.empty())
        return false;
    const int tableSize = 256;
    int hashTable[tableSize];
    for (unsigned int k = 0; k < tableSize; ++k)
    {
        hashTable[k] = 0;
    }
    int i = 0;
    while (str1[i]!='\0')
    {
        hashTable[str1[i++]] ++;
    }
    int j = 0;
    while (str2[j] != '\0')
    {
        hashTable[str2[j++]] --;
    }
    for (unsigned int k = 0; k < tableSize; ++k)
    {
        if (hashTable[k] != 0)
        {
            return false;
        }
    }
    return true;
}

int main()
{
    int n;
    cin >> n;
    cin.clear();
    cin.ignore();
    while (n--)
    {        
        string str1, str2;
        getline(cin, str1);
        getline(cin, str2);
        cout << test(str1, str2) << endl;
    }
    return 0;
}