检查字符串是否仅包含使用.at(int)的唯一字符

check if string contains only unique chars using .at(int)

本文关键字:int 唯一 字符 at 是否 字符串 包含使 检查      更新时间:2023-10-16

真正的基本问题,但我无法弄清楚。我的程序通过在字符串中找到数组中的每个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();

这不使用任何其他空间,并且适用于任何字符编码。