#UVa:10252-Common Permutation

灆洢 2015-01-15 01:53:33

計算兩個字串共同有的字母有哪些且有幾個,求出來即是答案。

C++(0.018)

/*******************************************************/
/* UVa 10252 Common Permutation                        */
/* Author: Maplewing [at] knightzone.studio            */
/* Version: 2015/01/15                                 */
/*******************************************************/
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

void countLetters(const string &s, int letterCount[]){
  for( int i = 0 ; i < s.length() ; ++i ){
    ++letterCount[(int)(s[i]-'a')];
  }
}

int main(){
  string a, b;
  while( getline(cin, a) ){
    getline(cin, b);
    int aLetterCount[30] = {0}, bLetterCount[30] = {0};
    countLetters(a, aLetterCount);
    countLetters(b, bLetterCount);

    for( int i = 0 ; i < 26 ; ++i ){
      int commonCount = min(aLetterCount[i], bLetterCount[i]);
      for( int j = 0 ; j < commonCount ; ++j ){
        printf("%c", (char)(i+'a'));
      }
    }
    printf("\n");
  }
  return 0;
}

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料