有人说是while(cin>>s){}的问题,有人说全局变量初始化的问题。
——————————————————————————分界线————————————
最后改完了,最终的代码好理解,但是初始代码还是不知道为什么会报错:
最终代码:
#include<iostream>
#include<string>
#include<unordered_set>
//C/C++库函数
// tolower() 实现字母的小写转换
// toupper() 实现字母的大写转换
// isalpha() 判断一个字符是否为字母,是返回非0,否返回0
// isalnum() 判断一个字符是否为数字或者字母,是返回非0,否返回0
// islower() 判断一个字符是否为小写字母,是返回非0,否返回0
// isupper() 判断一个字符是否为大写字母,是返回非0,否返回0
using namespace std;
void tranfer(string s,string keys)
{
string s1;
string result;
unordered_set<char>str1;
string str2 = "abcdefghijklmnopqrstuvwxyz";
for (auto str : s)
{
if (str1.count(str))continue;
str1.insert(str); s1 += str;
}
for (int i = 0; i < 26; i++)
{
if (str1.count(i + 'a'))continue;
s1 += (i + 'a');
}
for (auto str : keys)
{
for (int i = 0; i < 26; i++)
{
if (str2[i] == tolower(str))
{
if (islower(str))
{
result += s1[i];
}
else
result += toupper(s1[i]);
}
}
}
cout << result;
}
int main()
{
string s;
string keys;
while (cin>>s)
{
cin>>keys;
tranfer(s,keys);
}
return 0;
}
因为牛客里面案例都是小写,可以将这一步简化
for (auto str : keys)
{
for (int i = 0; i < 26; i++)
{
if (str2[i] == tolower(str))
{
if (islower(str))
{
result += s1[i];
}
else
result += toupper(s1[i]);
}
}
}
简化结果:
string res="";
for
(
int
i=0;i<s.size();i++){
//遍历判断
int
j=s[i]-
'a'
;
res+=x[j];
}
初始代码:经过验证 不是cin的问题
#include<iostream>
#include<string>
#include<unordered_set>
using namespace std;
void tranfer(string s)
{
string s1;
string s2;
string result;
unordered_set<char>str1;
string str2 = "abcdefghijklmnopqrstuvwxyz";
for (auto str : str2)
str1.insert(str);
for (auto str : s)
{
if (str1.find(str) != str1.end())
{
s1 += str;
str1.erase(str);
}
}
for (auto str : str1)
s1 += str;
string keys;
cin >> keys;
for (auto str : keys)
{
for (int i = 0; i < 26; i++)
{
if (str2[i] == tolower(str))
{
if (islower(str))
result += s1[i];
else
result += toupper(s1[i]);
}
}
}
cout << result;
}
int main()
{
string s;
while (cin>>s)
{
tranfer(s);
}
return 0;
}
————————————————分界线————————————————————
有头绪了,可能是因为 unordered_set<char>str 造成的!
unordered_set<char>str 输入的数据 输出后是不重复的,且是无序的。
跟输入的顺序也没有关系,因为底层实现原理是哈希表,所以输出的顺序受到哈希函数的影响。
其中,遇到重复字符插入时,选择 跳过检查语句 与不跳过 得到的结果是一样的。
最后:
c++ std
中set
与unordered_set
区别和map
与unordered_map
区别类似:
set
基于红黑树实现,红黑树具有自动排序的功能,因此map内部所有的数据,在任何时候,都是有序的。unordered_set
基于哈希表,数据插入和查找的时间复杂度很低,几乎是常数时间,而代价是消耗比较多的内存,无自动排序功能。底层实现上,使用一个下标范围比较大的数组来存储元素,形成很多的桶,利用hash
函数对key
进行映射到不同区域进行保存。