检查字符串是否仅包含使用.at(int)的唯一字符
check if string contains only unique chars using .at(int)
真正的基本问题,但我无法弄清楚。我的程序通过在字符串中找到数组中的每个ASCII的标志来检查字符串是否是唯一的。它不起作用(它编译了,但没有给出正确的答案(,我不能为自己的生命而弄清楚为什么。
我得到的输出为0:
main.cpp
#include "main.hpp"
#include <iostream>
bool isUnique(std::string str) {
if(str.length() > 128)
return false;
bool theChars[128];
for(int i = 0; i < str.length(); i++) {
int loc = str.at(i);
if(theChars[loc])
return false;
else
theChars[loc] = true;
}
return true;
}
int main() {
std::string timmy = "abcdefghijklmnop";
std::cout << isUnique(timmy);
return 0;
}
您忘了初始化bool数组:
bool theChars[128] = {};
空的初始化器表示为零的默认值,也就是bool。
false。 P.S。如果您在[0,127]之外有任何字符,则代码会产生未定义的行为。您可以通过使theChars
256长并在索引之前将角色施放到uint8_t
来解决此问题。或使用 std::array<char, 128>
和 theChars.at(loc)
进行异常。
更轻松的方法是使用 set
:
#include <iostream>
#include <set>
using namespace std;
bool isUnique(string str) {
set<char>st(str.begin(),str.end());
if(st.size()==str.size())
return true;
return false;
}
int main() {
string timmy = "abcdefghijklmnop";
cout << boolalpha<<isUnique(timmy)<<endl;
timmy = "aaaaabbbcdefghijklmnop";
cout << boolalpha<<isUnique(timmy)<<endl;
return 0;
}
P.S。如果不使用boolalpha
,它将为true
打印1,而false
的0。
std::sort(str.begin(), str.end());
return std::adjacent_find(str.begin(), str.end()) == str.end();
这不使用任何其他空间,并且适用于任何字符编码。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 何时在引用或唯一指针上使用移动语义
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 计算排序向量的向量中唯一值的计数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 检查字符串是否仅包含使用.at(int)的唯一字符
- 可以安全地使用静态强制转换,为每个实例使用唯一的虚拟 int type() 来提高性能