c++ - 检查字符串是否具有唯一字符

标签 c++ algorithm

我知道如何检查字符串是否具有唯一字符,但我想显示 NOT UNIQUE,即使它们的大小写不同

例如-我的算法

string = "dhAra"=> 唯一的

我认为更好的是它显示 NOT UNIQUE 因为它有两次 'a'

#include<iostream>

int main()
{
string str = "dhAra";
bool arr[128] = {0};

for (unsigned int i = 0; i < str.length() ; i++)
{
 int val = str[i];  //i think something needs to change here 
 cout << val << endl; 

 if(arr[val])
 { 
  cout << " not unique" ; 
  return 0; 
 }
 else
 { arr[val] = 1;} 
}
cout << "unique" ; 
return 0 ; 
}

最佳答案

您可以对所有字符使用 touppertolower 以确保捕获仅大小写不同的重复字符:

int val = toupper(str[i]); // tolower would be fine as well

作为旁注,在 C++ 中将 true 分配给 bool 的规范方法是

arr[val] = true; // rather than arr[val] = 1

虽然这两种方式都很好。

关于c++ - 检查字符串是否具有唯一字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15623573/

相关文章:

c++ - 如何实现 "Press Any Key To Exit"

algorithm - 什么情况下 Kruskal 没有达到最小值?

c++ - 使用 cublas sgemv 时如何跳过 float4 中的第四个元素?

c - 找到总和最大的 LIS

python - 条件检查场景中 eval 的替代方案

algorithm - 我应该改变什么才能得到积极的结果?

java - 我怎样才能修改这个递归回溯算法 (NQueens) 来找到所有的解决方案而不是一个?

c++ - 如何在编译时检查数组的大小

c++ - 接收大量 (r) UDP 流量时 CPU 负载高 (Windows)

c++ - 从C++ App获取PowerShell脚本输出