输出了其中一个Palindrome字符串:回文
- /************************************************************************/
- /* author: wcdj
- * date: 2009-10-3 (mid-autumn festival)
- * description:
- 如果给定的字符串从左到右和从右到左的序列完全一致,那么这样的字符串被称为palindrome。
- 例如,下面的字符串都是palindromes。
- "kayak"
- "codilitytilidoc"
- "neveroddoreven"
- 如果字符串A和字符串B含有相同的字母,但是顺序可能不一样,那么A被称为是B的anagram<易位构词,变位词>。
- 例如,下面的字符串互为anagrams:
- A="mary" B="army" A="rocketboys" B="octobersky" A="codility" B="codility"
- 实现一个函数
- int isAnagramOfPalindrome(char* str);
- 如果str的某种anagram是palindrome,则返回1,否则返回0。
- */
- /************************************************************************/
- #include <stdio.h>
- #include <string>
- #include <conio.h>//getch
- void instruction()
- {
- printf("----------------------------------/n");
- printf("/tPalindrome problem/n");
- printf("/tauthor: wcdj/n");
- printf("/tdate: 2009-10-3 (mid-autumn festival)/n");
- printf("----------------------------------/n/n");
- }
- int isAnagramOfPalindrome(char* str)
- {
- int nRes[26]={0};
- int n=0;
- for (int index=0;index!=strlen(str);index++)
- {
- n=str[index]-'a';
- nRes[n]++;//标记找到某一字母
- }
- for (int nOdd=0,nSum=0,index2=0;index2!=26;index2++)//遍历存储结果的数组
- {
- if (nRes[index2]==0)
- {
- continue;
- }
- else
- {
- nSum+=nRes[index2];//统计有多少个字母
- }
- if (nRes[index2]%2==1)//如果符合条件,则只能存在一个奇数
- {
- nOdd++;
- }
- if (nOdd>1)
- {
- return 0;
- }
- }
- //show a palindrome
- char* pPal=new char[nSum+1];
- pPal[nSum]='/0';
- for (int index3=0,i=0;index3!=26;index3++)
- {
- if (nRes[index3]==0)
- {
- continue;
- }
- int n=0;
- if (nRes[index3]%2!=1)
- {
- n=nRes[index3];
- while (n)
- {
- pPal[i]=pPal[nSum-1-i]='a'+index3;
- i++;
- n-=2;
- }
- }
- else
- {
- if (nSum%2==1)
- {
- pPal[nSum/2]='a'+index3;
- }
- }
- }
- printf("one of palindromes is: %s/n",pPal);
- delete []pPal;
- return 1;
- }
- void main()
- {
- instruction();
- printf("input a string:/n");
- char str[128]={0};
- scanf("%s",str);
- printf("str=%s/n",str);
- int nRes=isAnagramOfPalindrome(str);
- if (nRes==1)
- {
- printf("the string is a palindrome/n");
- }
- else
- {
- printf("the string is not a palindrome/n");
- }
- getch();
- return;
- }
学习:http://blog.youkuaiyun.com/delphiwcdj/article/details/4630969