您的位置:首页 > 其它

cracking the coding interview ch1.1

2013-12-24 12:50 337 查看
Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?

判断是否有重复字符

1 /*************************************************************************
2     > File Name: ch1.1.cc
3     > Author: purely
4     > Mail: godfantasy#gmail.com
5     > Created Time: 2013年12月24日 11:13:02
6  ************************************************************************/
7
8 #include<iostream>
9 #include<string>
10 using namespace std;
11 bool isUniqueA(const string& s)
12 {
13     bool check[255] = {0};
14     for(const char & c : s)
15     {
16         if(check[c] == 0)
17         {
18             check[c]++;
19         }
20         else
21         {
22             return false;
23         }
24     }
25
26     return true;
27 }
28
29 bool isUniqueB(const string& s)
30 {
31     for(int i = 0; i < s.length();i++)
32     {
33         const char & c = s[i];
34         for(int j = i + 1;j < s.length();j++)
35         {
36             if(c == s[j])
37             {
38                 return false;
39             }
40         }
41     }
42     return true;
43 }
44
45 int main()
46 {
47     string str("abcdefghijkl");
48     cout << str << ":" << isUniqueA(str) << endl;
49     cout << str << ":" << isUniqueB(str) << endl;
50     string str1("abcdefakldsajfjkdfjsal021830234'][");
51     cout << str1 << ":" << isUniqueA(str1) << endl;
52     cout << str1 << ":" << isUniqueB(str1) << endl;
53     return 0;
54 }
55


g++ (GCC) 4.8.2 编译

编译:

$ g++ -std=c++11 ch1.1.cc -o ch1.1

运行

$ ./ch1.1

abcdefghijkl:1

abcdefghijkl:1

abcdefakldsajfjkdfjsal021830234'][:0

abcdefakldsajfjkdfjsal021830234'][:0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: