作者:July,yansha。
时间:二零一一年四月二十三日。
致谢:老梦,nossiac,Hession,Oliver,luuillu,雨翔,啊菜,及微软100题实现小组所有成员。

微博:http://weibo.com/julyweibo
出处:http://blog.csdn.net/v_JULY_v
-------------------------------------------

目录
曲之前奏
第一节、一道俩个字符串是否包含的问题
  1.1、O(n*m)的轮询方法
  1.2、O(mlogm)+O(nlogn)+O(m+n)的排序方法
  1.3、O(n+m)的计数排序方法
第二节
  2.1、O(n+m)的hashtable的方法
  2.2、O(n+m)的数组存储方法
第三节、O(n)到O(n+m)的素数方法
第四节、字符串是否包含问题的继续补充
  4.1、Bit-map
  4.2、移位操作
第五节、字符串相关问题扩展
  5.1、字符串匹配问题
  5.2、在字符串中查找子串
    扩展:在一个字符串中找到第一个只出现一次的字符
  5.3、字符串转换为整数
  5.4、字符串拷贝

前奏

    前一章,请见这:程序员面试题狂想曲:第一章、左旋转字符串。本章里出现的所有代码及所有思路的实现,在此之前,整个网上都是没有的

    文中的思路,聪明点点的都能想到,巧的思路,大师也已奉献了。如果你有更好的思路,欢迎提供。如果你对此狂想曲系列有任何建议,欢迎微博上交流或来信指导。任何人,有任何问题,欢迎随时不吝指正。

    如果此狂想曲系列对你有所帮助,我会非常之高兴,并将让我有了永久坚持写下去的动力。谢谢。


第一节、一道俩个字符串是否包含的问题
1.0、题目描述:
假设这有一个各种字母组成的字符串,假设这还有另外一个字符串,而且这个字符串里的字母数相对少一些。从算法是讲,什么方法能最快的查出所有小字符串里的字母在大字符串里都有?

比如,如果是下面两个字符串:
String 1: ABCDEFGHLMNOPQRS
String 2: DCGSRQPOM
答案是true,所有在string2里的字母string1也都有。
  
如果是下面两个字符串:  
String 1: ABCDEFGHLMNOPQRS   
String 2: DCGSRQPOZ  
答案是false,因为第二个字符串里的Z字母不在第一个字符串里。

    点评:
    1、题目描述虽长,但题意简单明了,就是给定一长一短的俩个字符串A,B,假设A长B短,现在,要你判断B是否包含在字符串A中,即B?(-A。

    2、题意虽简单,但实现起来并不轻松,且当如果面试官步步紧逼,一个一个否决你能想到的方法,要你给出更好、最好的方案时,你恐怕就要伤不少脑筋了。

    ok,在继续往下阅读之前,您最好先想个几分钟,看你能想到的最好方案是什么,是否与本文最后实现的方法一致。


1.1、O(n*m)的轮询方法

判断string2中的字符是否在string1中?:
String 1: ABCDEFGHLMNOPQRS
String 2: DCGSRQPOM

    判断一个字符串是否在另一个字符串中,最直观也是最简单的思路是,针对第二个字符串string2中每一个字符,一一与第一个字符串string1中每个字符依次轮询比较,看它是否在第一个字符串string1中。

    假设n是字符串string1的长度,m是字符串string2的长度,那么此算法,需要O(n*m)次操作,拿上面的例子来说,最坏的情况下将会有16*8 = 128次操作

    我们不难写出以下代码:

 

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int CompareSting(string LongSting,string ShortSting)  
  5. {  
  6.     for (int i=0; i<ShortString.length(); i++)  
  7.     {  
  8.         for (int j=0; j<LongString.length(); j++)  //O(n*m)  
  9.         {  
  10.             if (LongString[i] == ShortString[j])  //一一比较  
  11.             {  
  12.                 break;  
  13.             }  
  14.               
  15.         }  
  16.         if (j==LongString.length())  
  17.         {  
  18.             cout << "false" << endl;  
  19.             return 0;  
  20.         }  
  21.     }  
  22.     cout << "true" << endl;  
  23.     return 1;  
  24. }  
  25.   
  26. int main()   
  27. {   
  28.     string LongString="ABCDEFGHLMNOPQRS";  
  29.     string ShortString="DCGSRQPOM";  
  30.     compare(LongString,ShortString);  
  31.     return 0;  
  32. }    

 

 上述代码的时间复杂度为O(n*m),显然,时间开销太大,我们需要找到一种更好的办法。

(网友acs713在本文评论下指出:个人的代码风格不规范,的确如此,后来看过<<代码大全>>之后,此感尤甚。个人会不断完善和规范此类代码风格。有任何问题,欢迎随时指正。谢谢大家。)

 

1.2、O(mlogm)+O(nlogn)+O(m+n)的排序方法
    一个稍微好一点的方案是先对这两个字符串的字母进行排序,然后同时对两个字串依次轮询。两个字串的排序需要(常规情况)O(m log m) + O(n log n)次操作,之后的线性扫描需要O(m+n)次操作

    同样拿上面的字串做例子,将会需要16*4 + 8*3 = 88加上对两个字串线性扫描的16 + 8 = 24的操作。(随着字串长度的增长,你会发现这个算法的效果会越来越好)

    关于采用何种排序方法,我们采用最常用的快速排序,下面的快速排序的代码用的是以前写的,比较好懂,并且,我执意不用库函数的qsort代码。唯一的问题是,此前写的代码是针对整数进行排序的,不过,难不倒我们,稍微改一下参数,即可,如下:

 

  1. //copyright@ 2011 July && yansha  
  2. //July,updated,2011.04.23.  
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6.   
  7. //以前的注释,还让它保留着  
  8. int partition(string &str,int lo,int hi)   
  9. {  
  10.     int key = str[hi];      //以最后一个元素,data[hi]为主元  
  11.     int i = lo - 1;  
  12.     for(int j = lo; j < hi; j++) ///注,j从p指向的是r-1,不是r。  
  13.     {  
  14.         if(str[j] <= key)  
  15.         {  
  16.             i++;  
  17.             swap(str[i], str[j]);  
  18.         }  
  19.     }  
  20.     swap(str[i+1], str[hi]);    //不能改为swap(&data[i+1],&key)  
  21.     return i + 1;   
  22. }  
  23.   
  24. //递归调用上述partition过程,完成排序。  
  25. void quicksort(string &str, int lo, int hi)  
  26. {  
  27.     if (lo < hi)  
  28.     {  
  29.         int k = partition(str, lo, hi);  
  30.         quicksort(str, lo, k - 1);  
  31.         quicksort(str, k + 1, hi);  
  32.     }  
  33. }  
  34.   
  35. //比较,上述排序O(m log m) + O(n log n),加上下面的O(m+n),  
  36. //时间复杂度总计为:O(mlogm)+O(nlogn)+O(m+n)。  
  37. void compare(string str1,string str2)  
  38. {  
  39.     int posOne = 0;  
  40.     int posTwo = 0;  
  41.     while (posTwo < str2.length() && posOne < str1.length())  
  42.     {  
  43.         while (str1[posOne] < str2[posTwo] && posOne < str1.length() - 1)  
  44.             posOne++;  
  45.         //如果和str2相等,那就不能动。只有比str2小,才能动。  
  46.           
  47.         if (str1[posOne] != str2[posTwo])  
  48.             break;  
  49.           
  50.         //posOne++;     
  51.         //归并的时候,str1[str1Pos] == str[str2Pos]的时候,只能str2Pos++,str1Pos不可以自增。  
  52.         //多谢helloword指正。  
  53.   
  54.         posTwo++;  
  55.     }  
  56.                   
  57.     if (posTwo == str2.length())  
  58.         cout << "true" << endl;  
  59.     else  
  60.         cout << "false" << endl;  
  61. }  
  62.   
  63. int main()   
  64. {   
  65.     string str1 = "ABCDEFGHLMNOPQRS";  
  66.     string str2 = "DCGDSRQPOM";    
  67.     //之前上面加了那句posOne++之所以有bug,是因为,@helloword:  
  68.     //因为str1如果也只有一个D,一旦posOne++,就到了下一个不是'D'的字符上去了,  
  69.     //而str2有俩D,posTwo++后,下一个字符还是'D',就不等了,出现误判。  
  70.   
  71.     quicksort(str1, 0, str1.length() - 1);  
  72.     quicksort(str2, 0, str2.length() - 1);  //先排序  
  73.     compare(str1, str2);                    //后线性扫描  
  74.     return 0;  
  75. }  

    

 

1.3、O(n+m)的计数排序方法

    此方案与上述思路相比,就是在排序的时候采用线性时间的计数排序方法,排序O(n+m),线性扫描O(n+m),总计时间复杂度为:O(n+m)+O(n+m)=O(n+m)

    代码如下:

 

  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. // 计数排序,O(n+m)  
  6. void CounterSort(string str, string &help_str)  
  7. {  
  8.     // 辅助计数数组  
  9.     int help[26] = {0};  
  10.   
  11.     // help[index]存放了等于index + 'A'的元素个数  
  12.     for (int i = 0; i < str.length(); i++)  
  13.     {  
  14.         int index = str[i] - 'A';  
  15.         help[index]++;  
  16.     }  
  17.   
  18.     // 求出每个元素对应的最终位置  
  19.     for (int j = 1; j < 26; j++)  
  20.         help[j] += help[j-1];  
  21.   
  22.     // 把每个元素放到其对应的最终位置  
  23.     for (int k = str.length() - 1; k >= 0; k--)  
  24.     {  
  25.         int index = str[k] - 'A';  
  26.         int pos = help[index] - 1;  
  27.         help_str[pos] = str[k];  
  28.         help[index]--;  
  29.     }  
  30. }  
  31.   
  32. //线性扫描O(n+m)  
  33. void Compare(string long_str,string short_str)  
  34. {  
  35.     int pos_long = 0;  
  36.     int pos_short = 0;  
  37.     while (pos_short < short_str.length() && pos_long < long_str.length())  
  38.     {  
  39.         // 如果pos_long递增直到long_str[pos_long] >= short_str[pos_short]  
  40.         while (long_str[pos_long] < short_str[pos_short] && pos_long < long_str.length  
  41.   
  42. () - 1)  
  43.             pos_long++;  
  44.           
  45.         // 如果short_str有连续重复的字符,pos_short递增  
  46.         while (short_str[pos_short] == short_str[pos_short+1])  
  47.             pos_short++;  
  48.   
  49.         if (long_str[pos_long] != short_str[pos_short])  
  50.             break;  
  51.           
  52.         pos_long++;  
  53.         pos_short++;  
  54.     }  
  55.       
  56.     if (pos_short == short_str.length())  
  57.         cout << "true" << endl;  
  58.     else  
  59.         cout << "false" << endl;  
  60. }  
  61.   
  62. int main()  
  63. {  
  64.     string strOne = "ABCDAK";  
  65.     string strTwo = "A";  
  66.     string long_str = strOne;  
  67.     string short_str = strTwo;  
  68.   
  69.     // 对字符串进行计数排序  
  70.     CounterSort(strOne, long_str);  
  71.     CounterSort(strTwo, short_str);  
  72.   
  73.     // 比较排序好的字符串  
  74.     Compare(long_str, short_str);  
  75.     return 0;  
  76. }  

 

 不过上述方法,空间复杂度为O(n+m),即消耗了一定的空间。有没有在线性时间,且空间复杂度较小的方案列?

 

第二节、寻求线性时间的解法
2.1、O(n+m)的hashtable的方法
    上述方案中,较好的方法是先对字符串进行排序,然后再线性扫描,总的时间复杂度已经优化到了:O(m+n),貌似到了极限,还有没有更好的办法列?

    我们可以对短字串进行轮询(此思路的叙述可能与网上的一些叙述有出入,因为我们最好是应该把短的先存储,那样,会降低题目的时间复杂度),把其中的每个字母都放入一个Hashtable里(我们始终设m为短字符串的长度,那么此项操作成本是O(m)或8次操作)。然后轮询长字符串,在Hashtable里查询短字符串的每个字符,看能否找到。如果找不到,说明没有匹配成功,轮询长字符串将消耗掉16次操作,这样两项操作加起来一共只有8+16=24次。
    当然,理想情况是如果长字串的前缀就为短字串,只需消耗8次操作,这样总共只需8+8=16次。

    或如梦想天窗所说: 我之前用散列表做过一次,算法如下:
 1、hash[26],先全部清零,然后扫描短的字符串,若有相应的置1,
 2、计算hash[26]中1的个数,记为m 
 3、扫描长字符串的每个字符a;若原来hash[a] == 1 ,则修改hash[a] = 0,并将m减1;若hash[a] == 0,则不做处理 
 4、若m == 0 or 扫描结束,退出循环。

    代码实现,也不难,如下:

 

  1. //copyright@ 2011 yansha  
  2. //July、updated,2011.04.25。   
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     string str1="ABCDEFGHLMNOPQRS";  
  10.     string str2="DCGSRQPOM";  
  11.   
  12.     // 开辟一个辅助数组并清零  
  13.     int hash[26] = {0};  
  14.   
  15.     // num为辅助数组中元素个数  
  16.     int num = 0;  
  17.   
  18.     // 扫描短字符串  
  19.     for (int j = 0; j < str2.length(); j++)  
  20.     {  
  21.         // 将字符转换成对应辅助数组中的索引  
  22.         int index = str1[j] - 'A';  
  23.   
  24.         // 如果辅助数组中该索引对应元素为0,则置1,且num++;  
  25.         if (hash[index] == 0)  
  26.         {  
  27.             hash[index] = 1;  
  28.             num++;  
  29.         }  
  30.     }  
  31.   
  32.     // 扫描长字符串  
  33.     for (int k = 0; k < str1.length(); k++)  
  34.     {  
  35.         int index = str1[k] - 'A';  
  36.   
  37.         // 如果辅助数组中该索引对应元素为1,则num--;为零的话,不作处理(不写语句)。  
  38.         if(hash[index] ==1)  
  39.         {  
  40.             hash[index] = 0;  
  41.             num--;  
  42.             if(num == 0)    //m==0,即退出循环。  
  43.                 break;  
  44.         }  
  45.     }  
  46.   
  47.     // num为0说明长字符串包含短字符串内所有字符  
  48.     if (num == 0)  
  49.         cout << "true" << endl;  
  50.     else  
  51.         cout << "false" << endl;  
  52.     return 0;  
  53. }  

 

 

2.2、O(n+m)的数组存储方法

    有两个字符串short_str和long_str。
    第一步:你标记short_str中有哪些字符,在store数组中标记为true。(store数组起一个映射的作用,如果有A,则将第1个单元标记true,如果有B,则将第2个单元标记true,... 如果有Z, 则将第26个单元标记true)
    第二步:遍历long_str,如果long_str中的字符包括short_str中的字符则将store数组中对应位置标记为false。(如果有A,则将第1个单元标记false,如果有B,则将第2个单元标记false,... 如果有Z, 则将第26个单元标记false),如果没有,则不作处理。
    第三步:此后,遍历store数组,如果所有的元素都是false,也就说明store_str中字符都包含在long_str内,输出true。否则,输出false。

    举个简单的例子好了,如abcd,abcdefg俩个字符串,
    1、先遍历短字符串abcd,在store数组中想对应的abcd的位置上的单元元素置为true,
    2、然后遍历abcdefg,在store数组中相应的abcd位置上,发现已经有了abcd,则前4个的单元元素都置为false,当我们已经遍历了4个元素,等于了短字符串abcd的4个数目,所以,满足条件,退出。
    (不然,继续遍历的话,我们会发现efg在store数组中没有元素,不作处理。最后,自然,就会发现store数组中的元素单元都是false的。)
    3、遍历store数组,发现所有的元素都已被置为false,所以程序输出true。

    其实,这个思路和上一节中,O(n+m)的hashtable的方法代码,原理是完全一致的,且本质上都采用的数组存储(hash表也是一个数组),但我并不认为此思路多此一举,所以仍然贴出来。ok,代码如下:

  1. //copyright@ 2011 Hession  
  2. //July、updated,2011.04.23.  
  3. #include<iostream>  
  4. #include<string.h>  
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     char long_ch[]="ABCDEFGHLMNOPQRS";  
  10.     char short_ch[]="DEFGHXLMNOPQ";  
  11.     int i;  
  12.     bool store[58];  
  13.     memset(store,false,58);    
  14.       
  15.     //前两个 是  遍历 两个字符串, 后面一个是  遍历 数组  
  16.     for(i=0;i<sizeof(short_ch)-1;i++)  
  17.         store[short_ch[i]-65]=true;  
  18.       
  19.     for(i=0;i<sizeof(long_ch)-1;i++)  
  20.     {  
  21.         if(store[long_ch[i]-65]!=false)  
  22.             store[long_ch[i]-65]=false;  
  23.     }  
  24.     for(i=0;i<58;i++)  
  25.     {  
  26.         if(store[i]!=false)  
  27.         {  
  28.             cout<<"short_ch is not in long_ch"<<endl;  
  29.             break;    
  30.         }          
  31.         if(i==57)  
  32.             cout<<"short_ch is in long_ch"<<endl;  
  33.     }  
  34.       
  35.     return 0;  
  36. }  

 

 

第三节、O(n)到O(n+m)的素数方法

    我想问的是,还有更好的方案么?
    你可能会这么想:O(n+m)是你能得到的最好的结果了,至少要对每个字母至少访问一次才能完成这项操作,而上一节最后的俩个方案是刚好是对每个字母只访问一次。

    ok,下面给出一个更好的方案:
    假设我们有一个一定个数的字母组成字串,我给每个字母分配一个素数,从2开始,往后类推。这样A将会是2,B将会是3,C将会是5,等等。现在我遍历第一个字串,把每个字母代表的素数相乘。你最终会得到一个很大的整数,对吧?
    然后——轮询第二个字符串,用每个字母除它。如果除的结果有余数,这说明有不匹配的字母。如果整个过程中没有余数,你应该知道它是第一个字串恰好的子集了。

思路总结如下:
1.定义最小的26个素数分别与字符'A'到'Z'对应。
2.遍历长字符串,求得每个字符对应素数的乘积。
3.遍历短字符串,判断乘积能否被短字符串中的字符对应的素数整除。
4.输出结果。

    至此,如上所述,上述算法的时间复杂度为O(m+n),时间复杂度最好的情况为O(n)(遍历短的字符串的第一个数,与长字符串素数的乘积相除,即出现余数,便可退出程序,返回false),n为长字串的长度,空间复杂度为O(1)。如你所见,我们已经优化到了最好的程度。

    不过,正如原文中所述:“现在我想告诉你 —— Guy的方案(不消说,我并不认为Guy是第一个想出这招的人)在算法上并不能说就比我的好。而且在实际操作中,你很可能仍会使用我的方案,因为它更通用,无需跟麻烦的大型数字打交道。但从”巧妙水平“上讲,Guy提供的是一种更、更、更有趣的方案。”

    ok,如果你有更好的思路,欢迎在本文的评论中给出,非常感谢。

  1. #include <iostream>  
  2. #include <string>  
  3. #include "BigInt.h"  
  4. using namespace std;  
  5.   
  6. // 素数数组  
  7. int primeNumber[26] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,  
  8.                         61, 67, 71, 73, 79, 83, 89, 97, 101};  
  9.   
  10. int main()  
  11. {  
  12.     string strOne = "ABCDEFGHLMNOPQRS";  
  13.     string strTwo = "DCGSRQPOM";  
  14.   
  15.     // 这里需要用到大整数  
  16.     CBigInt product = 1;   //大整数除法的代码,下头给出。  
  17.   
  18.     // 遍历长字符串,得到每个字符对应素数的乘积  
  19.     for (int i = 0; i < strOne.length(); i++)  
  20.     {  
  21.         int index = strOne[i] - 'A';  
  22.         product = product * primeNumber[index];  
  23.     }  
  24.   
  25.     // 遍历短字符串  
  26.     for (int j = 0; j < strTwo.length(); j++)  
  27.     {  
  28.         int index = strTwo[j] - 'A';  
  29.   
  30.         // 如果余数不为0,说明不包括短字串中的字符,跳出循环  
  31.         if (product % primeNumber[index] != 0)  
  32.             break;  
  33.     }  
  34.   
  35.     // 如果积能整除短字符串中所有字符则输出"true",否则输出"false"。  
  36.     if (strTwo.length() == j)  
  37.         cout << "true" << endl;  
  38.     else  
  39.         cout << "false" << endl;  
  40.     return 0;  
  41. }  

     上述程序待改进的地方:
1.只考虑大些字符,如果考虑小写字符和数组的话,素数数组需要更多素数
2.没有考虑重复的字符,可以加入判断重复字符的辅助数组。

 

以下的大整数除法的代码,虽然与本题目无多大关系,但为了保证文章的完整性,我还是决定把它贴出来,

代码如下(点击展开):

 

  1. //copyright@ 2011/03/06 yansha  
  2. //实现大整数类  
  3. #include <string>  
  4. #include <vector>  
  5. #include <iostream>  
  6. using namespace std;  
  7.   
  8. class CBigInt  
  9. {  
  10. public:  
  11.     // input  
  12.     friend istream& operator >> (istream &, CBigInt &);  
  13.     // output  
  14.     friend ostream& operator << (ostream &os, const CBigInt &value)  
  15.     {  
  16.         if (value.bigInt[0] == '-')  
  17.             os << value.bigInt;  
  18.         else  
  19.         {  
  20.             // 正数不输出符号  
  21.             os << value.bigInt.substr(1);  
  22.         }  
  23.         return os;  
  24.     }  
  25.     friend bool operator == (const CBigInt &, const CBigInt &);  
  26.     friend bool operator < (const CBigInt &lValue, const CBigInt &rValue)  
  27.     {  
  28.         if (lValue.bigInt[0] != rValue.bigInt[0])  
  29.         {  
  30.             // '+'ASCII码为43,'-'ASCII码为45  
  31.             return lValue.bigInt[0] > rValue.bigInt[0];  
  32.         }  
  33.         else  
  34.         {  
  35.             if (lValue.bigInt[0] == '+')  
  36.                 return lValue.smaller(rValue.bigInt);       // 正数的情况  
  37.             else  
  38.                 return lValue.greater(rValue.bigInt);       // 负数的情况  
  39.         }  
  40.     }  
  41.       
  42.     friend bool operator > (const CBigInt &lValue, const CBigInt &rValue)  
  43.     {  
  44.         if (lValue.bigInt[0] != rValue.bigInt[0])  
  45.             return lValue.bigInt[0] < rValue.bigInt[0];  
  46.         else  
  47.         {  
  48.             if (lValue.bigInt[0] == '+')  
  49.                 return lValue.greater(rValue.bigInt);  
  50.             else  
  51.                 return lValue.smaller(rValue.bigInt);  
  52.         }  
  53.     }  
  54.     string bigInt;  
  55. public:  
  56.     CBigInt();  
  57.     CBigInt(int);  
  58.     CBigInt(const string &);  
  59.     CBigInt(const CBigInt &);  
  60.     CBigInt(const char *);  
  61.     CBigInt& operator = (const CBigInt &);  
  62.     CBigInt& operator += (const CBigInt &);  
  63.     CBigInt& operator -= (const CBigInt &);  
  64.     CBigInt& operator *= (const CBigInt &);  
  65.     CBigInt& operator /= (const CBigInt &);  
  66.     CBigInt& operator %= (const CBigInt &);  
  67.       
  68.     // prefix increment  
  69.     CBigInt& operator ++ ();  
  70.     // prefix decrement  
  71.     CBigInt& operator -- ();  
  72.     // postfix increment  
  73.     CBigInt operator ++ (int);  
  74.     // postfix decrement  
  75.     CBigInt operator -- (int);  
  76. private:  
  77.     // unsigned +=  
  78.     void plus(const string &);  
  79.     // unsigned -=  
  80.     void minus(const string &);  
  81.     // unsigned ==  
  82.     bool equal(const string &) const;  
  83.     // unsigned <  
  84.     bool smaller(const string &) const;  
  85.     // unsigned >  
  86.     bool greater(const string &) const;  
  87. };  
  88.   
  89. /************************************************************************/  
  90. /* 构造函数                                                               
  91. /************************************************************************/  
  92. // 默认构造函数  
  93. inline CBigInt::CBigInt() : bigInt("+0")  
  94. {}  
  95.   
  96. // 构造函数  
  97. inline CBigInt::CBigInt(const string &str) : bigInt(str)  
  98. {  
  99.     if (bigInt.size() > 0)  
  100.     {  
  101.         // 没有正负符号  
  102.         if (bigInt[0] != '+' && bigInt[0] != '-')  
  103.         {  
  104.             string::size_type i = 0;  
  105.             for (; i < bigInt.size() - 1 && bigInt[i] == '0'; i++);  
  106.             if (i > 0)  
  107.                 bigInt.replace((string::size_type)0, i, "+");  
  108.             else  
  109.                 bigInt.insert((string::size_type)0, 1, '+');  
  110.         }   
  111.         else  
  112.         {  
  113.             if (bigInt.size() == 1)  
  114.                 bigInt = "+0";  
  115.             else  
  116.             {  
  117.                 string::size_type j = 1;  
  118.                 // 去掉多余的0  
  119.                 for (; j < bigInt.size() - 1 && bigInt[j] == '0'; j++);  
  120.                 if (j > 1)  
  121.                     bigInt.erase((string::size_type)1, j - 1);  
  122.                 if (bigInt == "-0")  
  123.                     bigInt = "+0";  
  124.             }  
  125.         }  
  126.     }   
  127.     else  
  128.         bigInt = "+0";  
  129. }  
  130.   
  131. // 复制构造函数  
  132. inline CBigInt::CBigInt(const CBigInt &value) : bigInt(value.bigInt)  
  133. {}  
  134.   
  135. inline CBigInt::CBigInt(int num)  
  136. {  
  137.     if (num == 0)  
  138.         bigInt = "+0";  
  139.     else if (num > 0)  
  140.         bigInt = '+';  
  141.     else  
  142.     {  
  143.         bigInt = '-';  
  144.         num *= -1;  
  145.     }  
  146.     string temp = "";  
  147.     while (num != 0)  
  148.     {  
  149.         temp += num % 10 + '0';  
  150.         num = num / 10;  
  151.     }  
  152.     for (int i = temp.size() - 1; i >= 0; i--)  
  153.         bigInt += temp[i];  
  154. }  
  155.   
  156. inline CBigInt::CBigInt(const char *str) : bigInt(str)  
  157. {  
  158.     if (bigInt.size() > 0)  
  159.     {  
  160.         if (bigInt[0] != '+' && bigInt[0] != '-')  
  161.         {  
  162.             string::size_type i = 0;  
  163.             // 去除多余的0  
  164.             for (; i < bigInt.size() - 1 && bigInt[i] == '0'; i++);  
  165.             if (i > 0)  
  166.                 bigInt.replace((string::size_type)0, i, "+");  
  167.             else  
  168.                 bigInt.insert((string::size_type)0, 1, '+');  
  169.         }   
  170.         else  
  171.         {  
  172.             if (bigInt.size() == 0)  
  173.                 bigInt = "+0";  
  174.             else  
  175.             {  
  176.                 string::size_type j = 1;  
  177.                 for (; j < bigInt.size() - 1 && bigInt[j] == '0'; j++);  
  178.                 if (j > 1)  
  179.                     bigInt.erase((string::size_type)1, j - 1);  
  180.                 // 处理特殊情况“-0”  
  181.                 if (bigInt == "-0")  
  182.                     bigInt = "+0";  
  183.             }  
  184.         }  
  185.     }   
  186.     else  
  187.         bigInt = "+0";  
  188. }  
  189.   
  190. inline bool operator == (const CBigInt &lValue, const CBigInt &rValue)  
  191. {  
  192.     return lValue.bigInt == rValue.bigInt;  
  193. }  
  194.   
  195. inline bool operator != (const CBigInt &lValue, const CBigInt &rValue)  
  196. {  
  197.     return !(lValue.bigInt == rValue.bigInt);  
  198. }  
  199.   
  200. inline bool operator <= (const CBigInt &lValue, const CBigInt &rValue)  
  201. {  
  202.     return !(lValue > rValue);  
  203. }  
  204.   
  205. inline bool operator >= (const CBigInt &lValue, const CBigInt &rValue)  
  206. {  
  207.     return !(lValue < rValue);  
  208. }  
  209.   
  210. inline CBigInt& CBigInt::operator = (const CBigInt &value)  
  211. {  
  212.     bigInt = value.bigInt;  
  213.     return *this;  
  214. }  
  215.   
  216. // unsigned ==  
  217. inline bool CBigInt::equal(const string &value) const  
  218. {  
  219.     return bigInt.substr(1) == value.substr(1);  
  220. }  
  221.   
  222. // unsigned <  
  223. inline bool CBigInt::smaller(const string &value) const  
  224. {  
  225.     if (bigInt.size() == value.size())  
  226.         return bigInt.substr(1) < value.substr(1);  
  227.     else  
  228.         return bigInt.size() < value.size();  
  229. }  
  230.   
  231. // unsigned >  
  232. inline bool CBigInt::greater(const string &value) const  
  233. {  
  234.     if (bigInt.size() == value.size())  
  235.         return bigInt.substr(1) > value.substr(1);  
  236.     else  
  237.         return bigInt.size() > value.size();  
  238. }  
  239.   
  240. /************************************************************************/  
  241. /* 实现+,-,*,/运算                                                                      
  242. /************************************************************************/  
  243. void CBigInt::plus(const string &value)  
  244. {  
  245.     if (bigInt.size() < value.size())  
  246.         bigInt.insert((string::size_type)1, (value.size() - bigInt.size()), '0');  
  247.     string::size_type i = bigInt.size() - 1;  
  248.     string::size_type j = value.size() - 1;  
  249.     while (j > 1)  
  250.     {  
  251.         bigInt[i] += value[j] - '0';  
  252.         if (bigInt[i] > '9')  
  253.         {  
  254.             bigInt[i] -= 10;  
  255.             ++bigInt[i-1];  
  256.         }  
  257.         i--;  
  258.         j--;  
  259.     }  
  260.       
  261.     // 最高位进位  
  262.     bigInt[i] += value[1] - '0';  
  263.     while (i > 1 && bigInt[i] > '9')  
  264.     {  
  265.         bigInt[i] -= 10;  
  266.         i--;  
  267.         ++bigInt[i];  
  268.     }  
  269.       
  270.     if (bigInt[1] > '9')  
  271.     {  
  272.         bigInt[1] -= 10;  
  273.         bigInt.insert((string::size_type)1, 1, '1');  
  274.     }  
  275. }  
  276.   
  277. void CBigInt::minus(const string &vlaue)  
  278. {  
  279.     string::size_type i = bigInt.size() - 1;  
  280.     string::size_type j = vlaue.size() - 1;  
  281.     while (j >= 1)  
  282.     {  
  283.         bigInt[i] -= vlaue[j] - '0';  
  284.         if (bigInt[i] < '0')  
  285.         {  
  286.             bigInt[i] += 10;  
  287.             --bigInt[i-1];  
  288.         }  
  289.         i--;  
  290.         j--;  
  291.     }  
  292.       
  293.     // 向前借位  
  294.     while (i > 1 && bigInt[i] < '0')  
  295.     {  
  296.         bigInt[i] += 10;  
  297.         i--;  
  298.         --bigInt[i];  
  299.     }  
  300.       
  301.     // 去除多余的0  
  302.     string::size_type k = 1;  
  303.     for (; k < bigInt.size() - 1 && bigInt[k] == '0'; k++);  
  304.     if (k > 1)  
  305.         bigInt.erase((string::size_type)1, k - 1);  
  306. }  
  307.   
  308. CBigInt& CBigInt::operator += (const CBigInt &value)  
  309. {  
  310.     if (bigInt[0] == value.bigInt[0])  
  311.         plus(value.bigInt);  
  312.     else  
  313.     {  
  314.         // 互为相反数的情况  
  315.         if (equal(value.bigInt))  
  316.             bigInt = "+0";  
  317.         // 绝对值小于的情况  
  318.         else if (smaller(value.bigInt))  
  319.         {  
  320.             string temp = bigInt;  
  321.             bigInt = value.bigInt;  
  322.             minus(temp);  
  323.         }  
  324.         else  
  325.             minus(value.bigInt);  
  326.     }  
  327.     return *this;  
  328. }  
  329.   
  330. CBigInt& CBigInt::operator -= (const CBigInt &value)  
  331. {  
  332.     // 处理过程与+=类似  
  333.     if (bigInt[0] == value.bigInt[0])  
  334.     {  
  335.         if (equal(value.bigInt))  
  336.             bigInt = "+0";  
  337.         else if (smaller(value.bigInt))  
  338.         {  
  339.             string temp = bigInt;  
  340.             bigInt = value.bigInt;  
  341.             minus(temp);  
  342.             if (bigInt[0] == '+')  
  343.                 bigInt[0] = '-';  
  344.             else  
  345.                 bigInt[0] = '+';  
  346.         }  
  347.         else  
  348.             minus(value.bigInt);  
  349.     }  
  350.     else  
  351.         plus(value.bigInt);  
  352.     return *this;  
  353. }  
  354.   
  355. CBigInt operator + (const CBigInt &lValue, const CBigInt &rValue)  
  356. {  
  357.     CBigInt sum(lValue);  
  358.     sum += rValue;  
  359.     return sum;  
  360. }  
  361.   
  362. CBigInt operator - (const CBigInt &lValue, const CBigInt &rValue)  
  363. {  
  364.     CBigInt diff(lValue);  
  365.     diff -= rValue;  
  366.     return diff;  
  367. }  
  368.   
  369. // prefix increment  
  370. CBigInt& CBigInt::operator ++ ()  
  371. {  
  372.     string::size_type i = bigInt.size() - 1;  
  373.     if (bigInt[0] == '+')  
  374.     {  
  375.         ++bigInt[i];  
  376.         while (i > 1 && bigInt[i] > '9')  
  377.         {  
  378.             bigInt[i] -= 10;  
  379.             i--;  
  380.             ++bigInt[i];  
  381.         }  
  382.           
  383.         if (bigInt[i] > '9')  
  384.         {  
  385.             bigInt[i] -= 10;  
  386.             bigInt.insert((string::size_type)1, 1, '1');  
  387.         }  
  388.     }   
  389.     else  
  390.     {  
  391.         --bigInt[i];  
  392.         while(i > 1 && bigInt[i] < '0')  
  393.         {  
  394.             bigInt[i] += 10;  
  395.             i--;  
  396.             --bigInt[i];  
  397.         }  
  398.           
  399.         string::size_type j = 1;  
  400.         for (; j < bigInt.size() - 1 && bigInt[j] == '0'; j++);  
  401.         if (j > 1)  
  402.             bigInt.erase(1, j - 1);  
  403.           
  404.         if (bigInt[1] == '0')  
  405.             bigInt[0] = '+';  
  406.     }  
  407.     return *this;  
  408. }  
  409.   
  410. CBigInt& CBigInt::operator -- ()  
  411. {  
  412.     string::size_type i = bigInt.size() - 1;  
  413.     // 对正数和负数分别处理  
  414.     if (bigInt[0] == '+')  
  415.     {  
  416.         // 对0进行处理  
  417.         if (bigInt[1] == '0')  
  418.             bigInt = "-1";  
  419.         else  
  420.         {  
  421.             --bigInt[i];  
  422.             while (i > 1 && bigInt[i] < '0')  
  423.             {  
  424.                 bigInt[i] += 10;  
  425.                 i--;  
  426.                 --bigInt[i];  
  427.             }  
  428.               
  429.             string::size_type j = 1;  
  430.             for (; j < bigInt.size() - 1 && bigInt[j] == '0'; j++);  
  431.             if (j > 1)  
  432.                 bigInt.erase(1, j - 1);  
  433.         }  
  434.     }  
  435.     else  
  436.     {  
  437.         ++bigInt[i];  
  438.         while (i > 1 && bigInt[i] > '9')  
  439.         {  
  440.             bigInt[i] -= 10;  
  441.             i--;  
  442.             ++bigInt[i];  
  443.         }  
  444.           
  445.         if (bigInt[1] > '9')  
  446.         {  
  447.             bigInt[1] += 10;  
  448.             bigInt.insert((string::size_type)1, 1, '1');  
  449.         }  
  450.     }  
  451.     return *this;  
  452. }  
  453.   
  454. // postfix increment  
  455. CBigInt CBigInt::operator ++ (int)  
  456. {  
  457.     CBigInt temp(*this);  
  458.     ++(*this);  
  459.     return temp;  
  460. }  
  461.   
  462. // postfix decrement  
  463. CBigInt CBigInt::operator -- (int)  
  464. {  
  465.     CBigInt temp(*this);  
  466.     --(*this);  
  467.     return temp;  
  468. }  
  469.   
  470. // 模拟笔算过程  
  471. CBigInt& CBigInt::operator *= (const CBigInt &value)  
  472. {  
  473.     // 乘数或被乘数有一方为0则返回结果0  
  474.     if (bigInt[1] == '0' || value.bigInt[1] == '0')  
  475.     {  
  476.         bigInt = "+0";  
  477.         return *this;  
  478.     }  
  479.       
  480.     string::size_type sizeofMultiplicand = bigInt.size();  
  481.     string::size_type sizeofMultiplier = value.bigInt.size();  
  482.     vector<unsigned int> product(sizeofMultiplier + sizeofMultiplicand - 1);  
  483.       
  484.     // 初始化  
  485.     for (string::size_type i = 1; i < sizeofMultiplicand; ++i)  
  486.         bigInt[i] -= '0';  
  487.       
  488.       
  489.     // 笔算乘法过程  
  490.     for (string::size_type j = sizeofMultiplier - 1; j > 0; --j)  
  491.     {  
  492.         if (value.bigInt[j] > '0')  
  493.         {  
  494.             for (string::size_type k = sizeofMultiplicand - 1; k > 0; --k)  
  495.                 product[k+j] += bigInt[k] * (value.bigInt[j] - '0');  
  496.         }  
  497.     }  
  498.       
  499.     // 处理符号  
  500.     if (bigInt[0] == value.bigInt[0])  
  501.         product[0] = '+';  
  502.     else  
  503.         product[0] = '-';  
  504.       
  505.     vector<unsigned int>::size_type sizeofProduct = product.size();  
  506.     bigInt = string(sizeofProduct, '0');  
  507.     bigInt[0] = product[0];  
  508.       
  509.     // 处理进位问题  
  510.     for (vector<unsigned int>::size_type n = sizeofProduct - 1; n > 1; --n)  
  511.     {  
  512.         product[n-1] += product[n] / 10;  
  513.         product[n] %= 10;  
  514.         bigInt[n] += product[n];  
  515.     }  
  516.       
  517.     if (product[1] == 0)  
  518.         bigInt.erase(1, 1);  
  519.     else  
  520.         bigInt[1] += product[1];  
  521.       
  522.     return *this;         
  523. }  
  524.   
  525. // 重复做差法求商  
  526. CBigInt& CBigInt::operator /= (const CBigInt &value)  
  527. {  
  528.     // 除数为0  
  529.     if (value.bigInt == "+0")  
  530.     {  
  531.         bigInt = "*Error!";  
  532.         return *this;  
  533.     }  
  534.       
  535.     // 被除数大于除数  
  536.     if (value.smaller(bigInt) == true)  
  537.     {  
  538.         string::size_type sizeofDividend = bigInt.size();  
  539.         string::size_type sizeofDivisor = value.bigInt.size();  
  540.         string answer(sizeofDividend, '0');  
  541.           
  542.         // 符号处理  
  543.         if (bigInt[0] == value.bigInt[0])  
  544.             answer[0] = '+';  
  545.         else  
  546.             answer[0] = '-';  
  547.           
  548.         string::size_type start = 1;  
  549.         string::size_type end = sizeofDivisor - 1;  
  550.           
  551.         while (end < sizeofDividend)  
  552.         {  
  553.             // 试商过程,从高位到低位  
  554.             while (value.greater(bigInt.substr(start - 1, end - start + 2)) ==   
  555.   
  556. false)  
  557.             {  
  558.                 string::size_type j = end;  
  559.                 // 减法过程  
  560.                 for (string::size_type i = sizeofDivisor - 1; i > 0; i--, j--)  
  561.                 {  
  562.                     bigInt[j] -= value.bigInt[i] - '0';  
  563.                     if (bigInt[j] < '0')  
  564.                     {  
  565.                         bigInt[j] += 10;  
  566.                         --bigInt[j-1];  
  567.                     }  
  568.                 }  
  569.                   
  570.                 // 商的相应位加1  
  571.                 ++answer[end];  
  572.                   
  573.                 // 以除数做边界去掉前缀0  
  574.                 while (start <= end && bigInt[start] == '0')  
  575.                     ++start;  
  576.             }  
  577.               
  578.             // 以被除数做边界去掉前缀0  
  579.             while (start < sizeofDividend && bigInt[start] == '0')  
  580.                 ++start;  
  581.               
  582.             // 如果end-start+1 < sizeofDivisor - 1,则进行补位  
  583.             if (end - start + 2 < sizeofDivisor)  
  584.                 end = sizeofDivisor + start - 2;  
  585.             else  
  586.                 ++end;  
  587.         }  
  588.         start = 1;  
  589.         for (; start < answer.size() - 1 && answer[start] == '0'; ++start);  
  590.         if (start > 1)  
  591.             answer.erase(1, start - 1);  
  592.   
  593.         bigInt = answer;  
  594.     }   
  595.     // 绝对值相等的情况  
  596.     else if (value.equal(bigInt) == true)  
  597.     {  
  598.         string answer = "-1";  
  599.         if (bigInt[0] == value.bigInt[0])  
  600.             answer = "+1";  
  601.         bigInt = answer;  
  602.     }  
  603.     else  
  604.         bigInt = "+0";  
  605.   
  606.     return *this;  
  607. }  
  608.   
  609. // 求余,与上面去商过程基本一致  
  610. CBigInt& CBigInt::operator %= (const CBigInt &value)  
  611. {  
  612.     if (value.bigInt == "+0")  
  613.     {  
  614.         bigInt = "*Error!";  
  615.         return *this;  
  616.     }  
  617.   
  618.     // 求余,余数为剩余bigInt值  
  619.     if (value.smaller(bigInt) == true)  
  620.     {  
  621.         string::size_type sizeofDivident = bigInt.size();  
  622.         string::size_type sizeofDivisor = value.bigInt.size();  
  623.   
  624.         string::size_type start = 1;  
  625.         string::size_type end = sizeofDivisor - 1;  
  626.         while (end < sizeofDivident)  
  627.         {  
  628.             // 除数的值不大于被除数的值  
  629.             while (value.greater(bigInt.substr(start - 1, end - start + 2)) ==   
  630.   
  631. false)  
  632.             {  
  633.                 string::size_type j = end;  
  634.                 for (string::size_type i = sizeofDivisor - 1; i > 0; --i, --j)  
  635.                 {  
  636.                     bigInt[j] -= value.bigInt[i] - '0';  
  637.                     if (bigInt[j] < '0')  
  638.                     {  
  639.                         bigInt[j] += 10;  
  640.                         --bigInt[j-1];  
  641.                     }  
  642.                 }  
  643.   
  644.                 while (start <= end && bigInt[start] == '0')  
  645.                     ++start;  
  646.             }  
  647.   
  648.             while (start < sizeofDivident && bigInt[start] == '0')  
  649.                 ++start;  
  650.   
  651.             if (end - start + 2 < sizeofDivisor)  
  652.                 end = sizeofDivisor + start - 2;  
  653.             else  
  654.                 ++end;  
  655.         }  
  656.   
  657.         start = 1;  
  658.         for (; start < sizeofDivident - 1 && bigInt[start] == '0'; start++);  
  659.   
  660.         if (start > 1)  
  661.             bigInt.erase(1, start - 1);  
  662.   
  663.         if (bigInt == "-0")  
  664.             bigInt[0] = '+';  
  665.     }  
  666.     else if (value.equal(bigInt))  
  667.         bigInt = "+0";  
  668.     return *this;  
  669. }  
  670.   
  671. CBigInt operator * (const CBigInt &lValue, const CBigInt &rValue)  
  672. {  
  673.     CBigInt product(lValue);  
  674.     product *= rValue;  
  675.     return product;  
  676. }  
  677.   
  678. CBigInt operator / (const CBigInt &lValue, const CBigInt &rValue)  
  679. {  
  680.     CBigInt quotient(lValue);  
  681.     quotient /= rValue;  
  682.     return quotient;  
  683. }  
  684.   
  685. CBigInt operator % (const CBigInt &lValue, const CBigInt &rValue)  
  686. {  
  687.     CBigInt mod(lValue);  
  688.     mod %= rValue;  
  689.     return mod;  
  690. }  

 

    说明:此次的判断字符串是否包含问题,来自一位外国网友提供的gofish、google面试题,这个题目出自此篇文章:http://www.aqee.net/2011/04/11/google-interviewing-story/,文章记录了整个面试的过程,比较有趣,值得一读。

    扩展:正如网友安逸所说:其实这个问题还可以转换为:a和b两个字符串,求b串包含a串的最小长度。包含指的就是b的字串包含a中每个字符。

 

第四节、字符串是否包含问题的继续补充
    updated:本文发布后,得到很多朋友的建议和意见,其中nossiac,luuillu等俩位网友除了给出具体的思路之外,还给出了代码,征得同意,下面,我将引用他们的的思路及代码,继续就这个字符串是否包含问题深入阐述。

    4.1、在引用nossiac的思路之前,我得先给你介绍下什么是Bit-map?
    Oliver:所谓的Bit-map就是用一个bit位来标记某个元素对应的Value, 而Key即是该元素。由于采用了Bit为单位来存储数据,因此在存储空间方面,可以大大节省。

    如果看了以上说的还没明白什么是Bit-map,那么我们来看一个具体的例子,假设我们要对0-7内的5个元素(4,7,2,5,3)排序(这里假设这些元素没有重复)。那么我们就可以采用Bit-map的方法来达到排序的目的。要表示8个数,我们就只需要8个Bit(1Bytes),首先我们开辟1Byte的空间,将这些空间的所有Bit位都置为0,如下图:

 

    然后遍历这5个元素,首先第一个元素是4,那么就把4对应的位置为1(可以这样操作:p+(i/8)|(0x01<<(i%8))当然了这里的操作涉及到Big-ending和Little-ending的情况,这里默认为Big-ending),因为是从零开始的,所以要把第五位置为一(如下图):

 

    接着再处理第二个元素7,将第八位置为1,,接着再处理第三个元素,一直到最后处理完所有的元素,将相应的位置为1,这时候的内存的Bit位的状态如下:

 

    最后我们现在遍历一遍Bit区域,将该位是一的位的编号输出(2,3,4,5,7),这样就达到了排序的目的。

    代码示例

 

  1. //位图的一个示例  
  2. //copyright@ Oliver && July   
  3. //http://blog.redfox66.com/post/2010/09/26/mass-data-4-bitmap.aspx  
  4. //July、updated,2011.04.25.  
  5.   
  6. #include <memory.h>  
  7. #include <stdio.h>  
  8. //定义每个Byte中有8个Bit位  
  9. #define BYTESIZE 8   
  10.   
  11. void SetBit(char *p, int posi)  
  12. {      
  13.     for(int i=0; i < (posi/BYTESIZE); i++)       
  14.     {         
  15.         p++;      
  16.     }        
  17.     *p = *p|(0x01<<(posi%BYTESIZE)); //将该Bit位赋值1     
  18.     return;  
  19. }    
  20.   
  21. void BitMapSortDemo()   
  22. {     
  23.     //为了简单起见,我们不考虑负数     
  24.     int num[] = {3,5,2,10,6,12,8,14,9};    
  25.   
  26.     //BufferLen这个值是根据待排序的数据中最大值确定的    
  27.     //待排序中的最大值是14,因此只需要2个Bytes(16个Bit)      
  28.     //就可以了。      
  29.     const int BufferLen = 2;      
  30.     char *pBuffer = new char[BufferLen];   
  31.       
  32.     //要将所有的Bit位置为0,否则结果不可预知。      
  33.     memset(pBuffer,0,BufferLen);      
  34.       
  35.     for(int i=0;i<9;i++)      
  36.     {          
  37.         //首先将相应Bit位上置为1          
  38.         SetBit(pBuffer,num[i]);     
  39.     }        
  40.       
  41.     //输出排序结果       
  42.     for(i=0;i<BufferLen;i++)   //每次处理一个字节(Byte)      
  43.     {           
  44.         for(int j=0;j<BYTESIZE;j++)   //处理该字节中的每个Bit位       
  45.         {              
  46.             //判断该位上是否是1,进行输出,这里的判断比较笨。           
  47.             //首先得到该第j位的掩码(0x01<<j),将内存区中的               
  48.             //位和此掩码作与操作。最后判断掩码是否和处理后的              
  49.             //结果相同             
  50.             if((*pBuffer&(0x01<<j)) == (0x01<<j))          
  51.             {                
  52.                 printf("%d ",i*BYTESIZE + j);        
  53.             }    
  54.         }    
  55.         pBuffer++;     
  56.     }  
  57.     printf("/n");  
  58. }     
  59.   
  60. int main()   
  61. {     
  62.     BitMapSortDemo();     
  63.     return 0;  
  64. }   

 

    位图总结
      1、可进行数据的快速查找,判重,删除,一般来说数据范围是int的10倍以下
      2、使用bit数组来表示某些元素是否存在,比如8位电话号码
      3、Bloom filter(日后介绍)可以看做是对bit-map的扩展

    问题实例
    1)已知某个文件内包含一些电话号码,每个号码为8位数字,统计不同号码的个数。 
       8位最多99 999 999,大概需要99m个bit,大概10几m字节的内存即可。 (可以理解为从0-99 999 999的数字,每个数字对应一个Bit位,所以只需要99M个Bit==12MBytes,这样,就用了小小的12M左右的内存表示了所有的8位数的电话)
    2)2.5亿个整数中找出不重复的整数的个数,内存空间不足以容纳这2.5亿个整数。
      将bit-map扩展一下,用2bit表示一个数即可,0表示未出现,1表示出现一次,2表示出现2次及以上,在遍历这些数的时候,如果对应位置的值是0,则将其置为1;如果是1,将其置为2;如果是2,则保持不变。或者我们不用2bit来进行表示,我们用两个bit-map即可模拟实现这个2bit-map,都是一样的道理。

    ok,介绍完了什么是bit-map,接下来,咱们回到正题,来看下nossiac关于此字符串是否包含问题的思路(http://www.shello.name/me/?p=64

每个字母的ASCII码值,可以对应一个位图中的位。 
先遍历第一个字符串,生成一个“位图字典”。

用伪代码表示就是:

 dictionary = 0
 for x in String1:
  dictionary |= 0x01<<x-'a'

红色部分就是构造位图字典的过程,刚好能运用ASCII码值完成,取巧,呵呵,比较惬意。

然后,我们遍历第二个字符串,用查字典的方式较检,伪代码为:

 for x in String2:
  if dictionary != dictionary|0x01<<x-'a':
  print("NO")
 else:
  print("YES")

what?还不够明白,ok,看yansha对此思路的具体阐述吧:
此思路是位操作的典型应用:
dictionary = 0
for x in String1:
   dictionary |= 0x01 << (x - 'a');

分析如下:
dictionary是一个32位的int,初始化为0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0


dictionary |= 0x01 << (x - 'a')则是把字符映射到dictionary当中的某一位;

 

 

比方String1 = "abde";
1、当x为‘a’时,x-‘a’为0,所以0x01<<0 为0x01。
那么dictionary |= 0x01,也就是将dictionary的第一位置1。
此时dictionary为:

1

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

 

 

2、当x为‘b’时,x-‘b’为1,所以0x01<<1 为0x02。
那么dictionary |= 0x02,也就是将dictionary的第二位置1。
此时dictionary为:

1

1

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

 

 

3、当x为‘d’时,x-‘d’为3,所以0x01<<3 为0x08。
那么dictionary |= 0x08,也就是将dictionary的第四位置1。
此时dictionary为:

1

1

0

1

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

 

 

4、当x为‘e’时,x-‘e’为4,所以0x01<<4 为0x10。
那么dictionary |= 0x10,也就是将dictionary的第五位置1。
此时dictionary为:

1

1

0

1

1

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

 

 

其他字符依此类推,比较过程也类似。对于128个字符的ASCII码而言,显然一个32位的整形是不够的。

OK,算法完成。时间复杂度为 O(m+n),空间复杂度为O(1)。

    然后,代码可以编写如下:

 

  1. //copyright@ nossiac  
  2. //July、updated,2011.04.24。  
  3. #include <stdio.h>  
  4. #include <string.h>  
  5.   
  6. #define getbit(x) (1<<(x-'a'))  
  7.   
  8. void a_has_b(char * a, char * b)  
  9. {  
  10.     int i = 0;  
  11.     int dictionary = 0;  
  12.     int alen = strlen(a);  
  13.     int blen = strlen(b);  
  14.       
  15.     for(i=0;i<alen;i++)  
  16.         dictionary |= getbit(a[i]);  
  17.       
  18.     for(i=0;i<blen;i++)  
  19.     {  
  20.         if(dictionary != (dictionary|getbit(b[i])))  
  21.             break;  
  22.     }  
  23.       
  24.     if(i==blen)  
  25.         printf("YES! A has B!/n");  
  26.     else  
  27.         printf("NiO!  Char at %d is not found in dictionary!/n",i);  
  28. }  
  29.   
  30. int main()  
  31. {  
  32.     char * str1="abcdefghijklmnopqrstuvwxyz";  
  33.     char * str2="akjsdfasdfiasdflasdfjklffhasdfasdfjklasdfjkasdf";  
  34.     char * str3="asdffaxcfsf";  
  35.     char * str4="asdfai";  
  36.       
  37.     a_has_b(str1, str2);  
  38.     a_has_b(str1, str3);  
  39.     a_has_b(str3, str4);  
  40.       
  41.     return 0;  
  42. }  

 

     4.2、还可以如luuillu所说,判断字符串是否包含,采用移位的方法(此帖子第745楼http://topic.csdn.net/u/20101126/10/b4f12a00-6280-492f-b785-cb6835a63dc9_8.html?seed=423056362&r=72955051#r_72955051,他的代码编写如下:

  1. //copyright@ luuillu  
  2. //July、updated,2011.04.24。  
  3. #include <iostream>      
  4. using namespace std;  
  5.   
  6. //判断  des 是否包含在 src 中  
  7. bool compare(char *des,char * src)  
  8. {  
  9.      unsigned  index[26]={1,2,4,8,16,32,64,128,256,512,1024,1<<11,  
  10.                           1<<12,1<<13,1<<14,1<<15,1<<16,1<<17,1<<18,1<<19,  
  11.                           1<<20,1<<21,1<<22,1<<23,1<<24,1<<25};    //2的n次幂  
  12.   
  13.      unsigned   srcdata=0;  
  14.      unsigned    desdata=0;  
  15.   
  16.      while( *src)  
  17.          srcdata|=index[(*src++)-'A'];  
  18.      while(*des)  
  19.          desdata|=index[(*des++)-'A'];  
  20.   
  21.      return     (srcdata|desdata) == srcdata    ;  
  22.    
  23. }  
  24.   
  25. int main()  
  26. {   
  27.     char *src="ABCDEFGHLMNOPQRS";     
  28.     char *des="DCGSRQPOM";     
  29.     cout<<compare(des,src)<<endl;     
  30.     return 0;     
  31. }  

 

    第四节总结:正如十一文章在本文评论里所提到的那样,上面的位图法,hash,还有bitmap三者之间并没有本质上的区别,只是形式上不同而已。

 

第五节、字符串相关问题扩展与阐述

5.1、字符串匹配问题
题目描述:
假设两个字符串中所含有的字符和个数都相同我们就叫这两个字符串匹配,比如:abcda和adabc,
由于出现的字符个数都是相同,只是顺序不同,所以这两个字符串是匹配的。

要求高效实现下面的函数: boolen Is_Match(char *str1,char *str2)。

    分析:可以看出,此字符串的匹配问题,是与上述字符串包含的问题相类似的,这个问题可以先排序再比较,也可以利用hash表进行判断。这里给出一种hash表的方法,原理已在上文中阐明了,代码如下:

  1. //copyright@ 2011 yansha   
  2. //July、updated,2011.04.24。  
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6.   
  7. bool Is_Match(const char *strOne,const char *strTwo)  
  8. {  
  9.     int lenOfOne = strlen(strOne);  
  10.     int lenOfTwo = strlen(strTwo);  
  11.   
  12.     // 如果长度不相等则返回false  
  13.     if (lenOfOne != lenOfTwo)  
  14.         return false;  
  15.   
  16.     // 开辟一个辅助数组并清零  
  17.     int hash[26] = {0};  
  18.       
  19.     // 扫描字符串  
  20.     for (int i = 0; i < strlen(strOne); i++)  
  21.     {  
  22.         // 将字符转换成对应辅助数组中的索引  
  23.         int index = strOne[i] - 'A';  
  24.           
  25.         // 辅助数组中该索引对应元素加1,表示该字符的个数  
  26.         hash[index]++;  
  27.     }  
  28.   
  29.     // 扫描字符串  
  30.     for (int j = 0; j < strlen(strTwo); j++)  
  31.     {  
  32.         int index = strTwo[j] - 'A';  
  33.           
  34.         // 如果辅助数组中该索引对应元素不为0则减1,否则返回false  
  35.         if (hash[index] != 0)  
  36.             hash[index]--;  
  37.         else  
  38.             return false;  
  39.     }  
  40.     return true;  
  41. }  
  42.   
  43. int main()  
  44. {  
  45.     string strOne = "ABBA";  
  46.     string strTwo = "BBAA";  
  47.       
  48.     bool flag = Is_Match(strOne.c_str(), strTwo.c_str());  
  49.       
  50.     // 如果为true则匹配,否则不匹配  
  51.     if (flag == true)  
  52.         cout << "Match" << endl;  
  53.     else  
  54.         cout << "No Match" << endl;  
  55.     return 0;  
  56. }  

 

 

5.2、在字符串中查找子串
题目描述:
给定一个字符串A,要求在A中查找一个子串B。
如A="ABCDF",要你在A中查找子串B=“CD”。

    分析:比较简单,相当于实现strstr库函数,主体代码如下:

  1. //copyright@ 2011 July && luoqitai    
  2. //2013/4/16  updated  
  3. //string为模式串,substring为要查找的子串  
  4. int strstr(char *string,char *substring)     
  5. {    
  6.     int len1=strlen(string);    
  7.     int len2=strlen(substring);    
  8.     for (int i=0; i<=len1-len2; i++)   //复杂度为O(m*n)    
  9.     {    
  10.         for (int j=0; j<len2; j++)    
  11.         {    
  12.             if (string[i+j]!=substring[j])    
  13.                 break;    
  14.               
  15.             //多谢小明_ML指正  
  16.             if (j==len2-1)    
  17.                 return 1;    
  18.         }  
  19.     }    
  20.     return 0;    
  21. }     

 

    上述程序已经实现了在字符串中查找第一个子串的功能,时间复杂度为O(n*m),继续的优化可以先对两个字符串进行排序,然后再查找,也可以用KMP算法,复杂度为O(m+n)。具体的,在此不再赘述(多谢hlm_87指正)。 

    扩展:还有个类似的问题:第17题(字符串):题目:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。代码,可编写如下(测试正确):

 

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. //查找第一个只出现一次的字符,第1个程序  
  5. //copyright@ Sorehead && July  
  6. //July、updated,2011.04.24.  
  7. char find_first_unique_char(char *str)  
  8. {  
  9.     int data[256];  
  10.     char *p;  
  11.       
  12.     if (str == NULL)  
  13.         return '/0';  
  14.       
  15.     memset(data, 0, sizeof(data));    //数组元素先全部初始化为0  
  16.     p = str;  
  17.     while (*p != '/0')  
  18.         data[(unsigned char)*p++]++;  //遍历字符串,在相应位置++,(同时,下标强制转换)  
  19.       
  20.     while (*str != '/0')  
  21.     {  
  22.         if (data[(unsigned char)*str] == 1)  //最后,输出那个第一个只出现次数为1的字符  
  23.             return *str;  
  24.           
  25.         str++;  
  26.     }  
  27.       
  28.     return '/0';  
  29. }  
  30.   
  31. int main()  
  32. {  
  33.     char *str = "afaccde";  
  34.     cout << find_first_unique_char(str) << endl;  
  35.     return 0;  
  36. }  

  当然,代码也可以这么写(测试正确): 

 

 

  1. //查找第一个只出现一次的字符,第2个程序  
  2. //copyright@ yansha  
  3. //July、updated,2011.04.24.  
  4. char FirstNotRepeatChar(char* pString)  
  5. {  
  6.     if(!pString)  
  7.         return '/0';  
  8.       
  9.     const int tableSize = 256;  
  10.     int hashTable[tableSize] = {0}; //存入数组,并初始化为0  
  11.       
  12.     char* pHashKey = pString;  
  13.     while(*(pHashKey) != '/0')  
  14.         hashTable[*(pHashKey++)]++;  
  15.       
  16.     while(*pString != '/0')  
  17.     {  
  18.         if(hashTable[*pString] == 1)  
  19.             return *pString;  
  20.           
  21.         pString++;  
  22.     }  
  23.     return '/0';  //没有找到满足条件的字符,退出  
  24. }  

 

5.3、字符串转换为整数
题目:输入一个表示整数的字符串,把该字符串转换成整数并输出。
例如输入字符串"345",则输出整数345。

    分析:此题看起来,比较简单,每扫描到一个字符,我们把在之前得到的数字乘以10再加上当前字符表示的数字。这个思路用循环不难实现。然其背后却隐藏着不少陷阱,正如zhedahht 所说,有以下几点需要你注意:
    1、由于整数可能不仅仅之含有数字,还有可能以'+'或者'-'开头,表示整数的正负。如果第一个字符是'+'号,则不需要做任何操作;如果第一个字符是'-'号,则表明这个整数是个负数,在最后的时候我们要把得到的数值变成负数。
    2、如果使用的是指针的话,在使用指针之前,我们要做的第一件是判断这个指针是不是为空。如果试着去访问空指针,将不可避免地导致程序崩溃(此第2点在下面的程序不需注意,因为没有用到指针)。
    3、输入的字符串中可能含有不是数字的字符。
每当碰到这些非法的字符,我们就没有必要再继续转换。
    4、溢出问题。由于输入的数字是以字符串的形式输入,因此有可能输入一个很大的数字转换之后会超过能够表示的最大的整数而溢出。

    总结以上四点,代码可以如下编写:

 

  1. //字符串转换为整数  
  2. //copyright@ yansha  
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6.   
  7. int str_2_int(string str)  
  8. {  
  9.     if (str.size() == 0)  
  10.         exit(0);  
  11.       
  12.     int pos = 0;  
  13.     int sym = 1;  
  14.       
  15.     // 处理符号  
  16.     if (str[pos] == '+')  
  17.         pos++;  
  18.     else if (str[pos] == '-')  
  19.     {  
  20.         pos++;  
  21.         sym = -1;  
  22.     }  
  23.       
  24.     int num = 0;  
  25.     // 逐位处理  
  26.     while (pos < str.length())  
  27.     {  
  28.         // 处理数字以外的字符  
  29.         if (str[pos] < '0' || str[pos] > '9')  
  30.             exit(0);  
  31.           
  32.         num = num * 10 + (str[pos] - '0');  
  33.           
  34.         // 处理溢出  
  35.         if (num < 0)  
  36.             exit(0);      
  37.         pos++;  
  38.     }  
  39.       
  40.     num *= sym;   
  41.     return num;  
  42. }  
  43.   
  44. int main()  
  45. {  
  46.     string str = "-3450";  
  47.     int num = str_2_int(str);  
  48.     cout << num << endl;  
  49.     return 0;  
  50. }  

 

    @helloword:这个的实现非常不好,当输入字符串参数为非法时,不是抛出异常不是返回error code,而是直接exit了。直接把进程给终止了,想必现实应用中的实现都不会这样。建议您改改,不然拿到面试官那,会被人喷死的。ok,听从他的建议,借用zhedahht的代码了:

 

  1. //http://zhedahht.blog.163.com/blog/static/25411174200731139971/  
  2. enum Status {kValid = 0, kInvalid};  
  3. int g_nStatus = kValid;  
  4.   
  5. int StrToInt(const char* str)  
  6. {  
  7.     g_nStatus = kInvalid;  
  8.     long long num = 0;  
  9.       
  10.     if(str != NULL)  
  11.     {  
  12.         const char* digit = str;  
  13.           
  14.         // the first char in the string maybe '+' or '-'  
  15.         bool minus = false;  
  16.         if(*digit == '+')  
  17.             digit ++;  
  18.         else if(*digit == '-')  
  19.         {  
  20.             digit ++;  
  21.             minus = true;  
  22.         }  
  23.           
  24.         // the remaining chars in the string  
  25.         while(*digit != '/0')  
  26.         {  
  27.             if(*digit >= '0' && *digit <= '9')  
  28.             {  
  29.                 num = num * 10 + (*digit - '0');  
  30.                   
  31.                 // overflow    
  32.                 if(num > std::numeric_limits<int>::max())  
  33.                 {  
  34.                     num = 0;  
  35.                     break;  
  36.                 }  
  37.                   
  38.                 digit ++;  
  39.             }  
  40.             // if the char is not a digit, invalid input  
  41.             else  
  42.             {  
  43.                 num = 0;  
  44.                 break;  
  45.             }  
  46.         }  
  47.           
  48.         if(*digit == '/0')  
  49.         {  
  50.             g_nStatus = kValid;  
  51.             if(minus)  
  52.                 num = 0 - num;  
  53.         }  
  54.     }  
  55.       
  56.     return static_cast<int>(num);  
  57. }  

 

updated:yansha看到了上述helloword的所说的后,修改如下:

 

  1. #include <iostream>  
  2. #include <string>  
  3. #include <assert.h>  
  4. using namespace std;  
  5.   
  6. int str_2_int(string str)  
  7. {  
  8.     assert(str.size() > 0);  
  9.       
  10.     int pos = 0;  
  11.     int sym = 1;  
  12.       
  13.     // 处理符号  
  14.     if (str[pos] == '+')  
  15.         pos++;  
  16.     else if (str[pos] == '-')  
  17.     {  
  18.         pos++;  
  19.         sym = -1;  
  20.     }  
  21.       
  22.     int num = 0;  
  23.     // 逐位处理  
  24.     while (pos < str.length())  
  25.     {  
  26.         // 处理数字以外的字符  
  27.         assert(str[pos] >= '0');  
  28.         assert(str[pos] <= '9');  
  29.           
  30.         num = num * 10 + (str[pos] - '0');  
  31.           
  32.         // 处理溢出  
  33.         assert(num >= 0);  
  34.           
  35.         pos++;  
  36.     }  
  37.       
  38.     num *= sym;  
  39.       
  40.     return num;  
  41. }  
  42.   
  43. int main()  
  44. {  
  45.     string str = "-1024";  
  46.     int num = str_2_int(str);  
  47.     cout << num << endl;  
  48.     return 0;  
  49. }  

  

 

5.4、字符串拷贝
题目描述:
    要求实现库函数strcpy,

原型声明:extern char *strcpy(char *dest,char *src); 
功能:把src所指由NULL结束的字符串复制到dest所指的数组中。  
说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。  
返回指向dest的指针。

    分析:如果编写一个标准strcpy函数的总分值为10,下面给出几个不同得分的答案:

  1. //2分  
  2. void strcpy( char *strDest, char *strSrc )  
  3. {  
  4.     while( (*strDest++ = * strSrc++) != '/0' );  
  5. }   
  6.   
  7. //4分  
  8. void strcpy( char *strDest, const char *strSrc )   
  9. {  
  10.     //将源字符串加const,表明其为输入参数,加2分  
  11.     while( (*strDest++ = * strSrc++) != '/0' );  
  12. }   
  13.   
  14. //7分  
  15. void strcpy(char *strDest, const char *strSrc)   
  16. {  
  17.     //对源地址和目的地址加非0断言,加3分  
  18.     assert( (strDest != NULL) && (strSrc != NULL) );  
  19.     while( (*strDest++ = * strSrc++) != '/0' );  
  20. }   
  21.   
  22. //10分  
  23. //为了实现链式操作,将目的地址返回,加3分!  
  24. char * strcpy( char *strDest, const char *strSrc )   
  25. {  
  26.     assert( (strDest != NULL) && (strSrc != NULL) );  
  27.     char *address = strDest;   
  28.     while( (*strDest++ = * strSrc++) != '/0' );   
  29.     return address;  
  30. }   

 

勘误:上述字符串拷贝的写法有点问题,正如本文评论下留言的读者paranoid2006所述:字符串拷贝的问题,虽然限定源字符串为const,但是不能防止src和dest有overlap,层叠的问题。也就是在拷贝src到dest的中途会导致dest覆盖部分src的字符串。
当dest+strlen(src)大于src或者src+strlen(src)大于dest均有可能导致覆盖。

除了此题外,本文其它函数的编写也存在不少问题,日后统一修正! 欢迎读者继续批评指正,谢谢。July、二零一二年九月二十三日。

联系作者: 
微博:http://weibo.com/julyweibo @ July,http://weibo.com/yanshazi @ yansha。
邮箱:zhoulei0907@yahoo.cn @ July,yansha0@hotmail.com @ yansha。

posted on 2013-05-16 00:02  知识天地  阅读(436)  评论(0编辑  收藏  举报