打好基本功:
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.
An extra copy of the array is not.
FOLLOW UP
Write the test cases for this method.
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
----------------------------------------------------------
明天參加微軟校園日,回來繼續補充!
-----------------------------------------------------------
昨天體力不支,荒廢了一天!今天繼續第一天沒有解決的問題。
如果可以開一個固定大小的數組(與輸入的規模無關),與第一題思想類似,若是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";//重複字符不連續