字符串是否有相同的字母

来源:互联网 发布:破解视频聊天软件 编辑:程序博客网 时间:2024/05/24 06:29

一个字符串是否有相同的字母!!

此题如不要使用额外空间的话,可用朴素的O(n^2)的方法,俩次大循环比较。

此题复习了下bitset,string。发现c++中无stingbuffer

下一个帖子转载他人关于string 与 bitset 实现。

#include <iostream>#include <string>#include <bitset>using namespace std;bool isunique_char(string str);bool isunique_bit(string str);int main(){string str;cin>>str;cout <<"------------------"<<endl;if(isunique_char(str)){cout<<"true"<<endl;}else{cout<<"false"<<endl;}cout <<"------------------"<<endl;if(isunique_bit(str)){cout<<"true"<<endl;}else{cout<<"false"<<endl;}cout <<"------------------"<<endl;return 1;}//实现一个字符串是否有相同的字符//假设为ASCII//以bool数组实现bool isunique_char(string str){if (str.length() > 256)//减少判断!{return false;}//bool check[256] ;bool *check = new bool[256];memset(check ,0,sizeof(bool)*256 ); //如果不初始化将产生意想不到的结果!/*for(int j = 0; j < 256; j++){check[j] = false;}*/for (int i = 0; i < str.length(); i++){if (check[str[i]]){delete check;return false;}check[str[i]] = true;}delete check;return true;}//总结 //对于全局变量,静态变量,均由编译器自动初始化// 自动变量未初始化,从本例来看很可能全1!!!// 对于 new 为 分配内存+构造函数--已初始化//malloc  只分配内存//calloc 分配内存+清0//数组简单初始化法 int A[100] = {0} //缺省的都为0bool isunique_bit(string str){if (str.length() > 256)//减少判断!{return false;}bitset<256> vector_bit(0);//默认初始化了,构造函数!!好处for (int i = 0; i < str.length(); i++){if (vector_bit[str.at(i)]){return false;}vector_bit[str.at(i)] = true;}return true;}//bitset  的使用 --- 在大数据中使用广泛!!//template <size_t N> class bitset;// 常用的: 随机访问[],set(i),set(i,0).//cout() 统计1的个数//reset清空//size//any


0 0
原创粉丝点击