简单的面试题小练习。

来源:互联网 发布:男生双肩包 知乎 编辑:程序博客网 时间:2024/05/09 05:55

最近在准备看一看《Cracking the coding interview》,有蛮多程序员面试题目的,在网上也比较容易搜到答案。

就从简单的开始吧,前几天CFree过试用期了,下的DEV C++也不知道咋回事用不了,就用以前装的Visual Studio了。。。

Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?

实现一个算法判断一个字符串中的字符是否唯一,即不重复,不适用额外的数据结构。

不适用额外的数据结构,应该说的是只能使用基础的数据结构。

使用一个256个元素的数组来存储字符是否在字符串中已存在,可以用bool(sizeof = 1)类型的数组直接判断true和false,也可以用int(sizeof = 4)类型来计算字符出现的次数,最后扫描数组判断是否有大于1的值。

#include "stdafx.h"#include "string.h"bool CheckString1(char * str){bool a[256];memset(a,0,sizeof(a));int value;while(*str != '\0'){value = (int)*str;if(a[value] == false)a[value] = true;elsereturn false;str++;}return true;}int _tmain(int argc, _TCHAR* argv[]){char * str1 = "abcdefghijklmnopqrstuvwxyz1234567890";char * str2 = "helloworld helloworld ";printf("%d\n",CheckString1(str1));printf("%d\n",CheckString1(str2));int i = 0;scanf("%d",&i);return 0;}