cracking the code interview——c++實現

本系列是我對cracking the code interviews的c++實現和學習,不足之處歡迎批評指正。

題目:實現一個算法,判斷其中的字符是否都不相同。如果不能用數據結構,又該如何實現?

解:首先得向面試官問清楚是Unicode還是ASCII編碼,這裏我們假設爲ASCII編碼。具體代碼實現如下:

#include<iostream>
#include<string>
using namespace std;

bool isalldifferent(string s){
if(s.length()==0)
return false;
int* p=new int[256];
for(int i=0;i<s.length();i++){
if(p[int(s[i])]==1)
return false;
p[int(s[i])]=1;
}
return true;
}
int main(){
string s="abcdef{?><";
cout<<isalldifferent(s)<<endl;
system("pause");
return 0;
}

發佈了65 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章