打好基本功:
Data Structures | Algorithms | Concepts |
Linked Lists | Breadth First Search | Bit Manipulation |
Binary Trees | Depth First Search | Singleton Design Pattern |
Tries | Binary Search | Factory Design Pattern |
Stacks | Merge Sort | Memory (Stack vs Heap) |
Queues | Quick Sort | Recursion |
Vectors / ArrayLists | Tree Insert / Find / etc | Big-O Time |
Hash Tables |
Chapter 1 | Arrays and Strings
问题:
1.1 Implement an algorithm to determine if a string has all unique characters What if you
can not use additional data structures?
翻译:不用额外的数据结构来实现一个算法判断一个字符串中的所有字符是否唯一(没有重复)?
对于问题本身需要清楚:字符是ASCII还是字母。
假设是ASCII字符(ASCII 码使用指定的7 位或8 位二进制数组合来表示128 或256 种可能的字符。7 位二进制数来表示所有的大写和小写字母,数字0 到9、标点符号, 以及在美式英语中使用的特殊控制字符,后128个称为扩展ASCII码。)
bool isUniqueChar(string s)
{
bool a[256];
memset(a,0,sizeof(a));//memset函数:将s所指向的某一块内存中的
//每个字节的内容全部设置为ch指定的ASCII值
int len = s.length();
for(int i=0; i < len;++i)
{
int value = (int)s[i];
if(a[value])return false;
a[value] = true;
}
return true;
}
该算法时间复杂度为O(n)。
通过位运算来改进上述算法。
假设是字母字符(a-z或A-Z)
bool isUniqueChar2(string s)
{
int check = 0;
int len = s.length();
for(int i=0; i < len; ++i)
{
int v = (int)(s[i]-'a');
if(check & (1 << v)) return false;
check |= (1<
1.2 Write code to reverse a C-Style String (C-String means that “abcd” is represented as five characters, including the null character )
翻译:写代码翻转C风格字符串(C风格字符串指“abcd”代表5个字符,其中包括最后的结束符。)
顺便一提,string字符串和char字符以及char*的区别。
void reverseChars(char *str)
{
char *end = str;
char tmp;
if(str)
{
while(*end)
{
++end;
}
--end;
while(str
另一种方法:
void reverseChars2(char str[])
{
int i,j;
for(i=0,j=strlen(str)-1;i
1.3 Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer NOTE: One or two additional variables are fine
An extra copy of the array is not.
FOLLOW UP
Write the test cases for this method.
翻译:设计算法并写出代码,在一个字符串中去掉重复字符,不能用额外的缓存空间,允许一到两个变量,不允许拷贝数组,编写测试用例。
void removeDuplicates(char str[])
{
if(str == NULL)return;//str is null,return.
int len = strlen(str);
if(len <2)return;//str has one character,no duplicates.
int tail =1;
for(int i = 1;i
该算法时间复杂度O(n^2)。还有改进的空间?
----------------------------------------------------------
明天参加微软校园日,回来继续补充!
-----------------------------------------------------------
昨天体力不支,荒废了一天!今天继续第一天没有解决的问题。
如果可以开一个固定大小的数组(与输入的规模无关),与第一题思想类似,若是ASCII字符就开一个大小为256的数组,那么只要遍历一遍字符串即可,时间复杂度为O(n)。见上面removeDuplicates3
如果字符集为a-z或A-Z则只需额外开一个变量,且时间复杂度为O(n) 。见上面removeDuplicates4
下面是测试用例:
1.char s1[] = "abcd";//没有重复字符
2.char s2[] = "aaaa";//全是重复字符
3.char s3[] ="";//空字符串
4.char s4[] = "aaabbb";//重复字符连续出现
5.char s5[] = "ababa";//重复字符不连续