2018年3月15日 星期四

[C_ST108-易] 重組字(C++)

[C_ST108-易] 重組字

Time Limit: 2 seconds
問題描述 :
所謂「重組字」是將單字或片語中的字母重新排列組合而造出來的單字或片語。其中的空白可以忽略,字母的大小寫不考慮,且每個字母出現的次數必須一樣,例如, Dormitory 的重組字可以是 Dirty Room 。
輸入說明 :
每個輸入有 5 筆測資,每筆測資一行,每一行包含 2 個單字或片語,中間以破折號 「 - 」 為區隔。
輸出說明 :
輸出每一筆測資是否為 重組字,正確輸出 true ,錯誤輸出 false 。
範例 :

輸入範例輸出範例
Dormitory - Dirty room
keep - peek
silent - listen
Toss - Shot
Joy - enjoy
true
true
true
false
false

  1. #include <iostream>  
  2. #include <string>  
  3. #include <sstream>  
  4. #include <stdio.h>  
  5. #include <ctype.h>  
  6. using namespace std;  
  7.   
  8. int main() {  
  9.     // [C_ST108-易] 重組字  
  10.     string test;  
  11.     while(getline(cin, test))  
  12.     {  
  13.         string s1, s2;  
  14.         stringstream ss(test);  
  15.         string token;  
  16.         int c = 0;  
  17.         //字串切割  
  18.         while (getline(ss, token, '-'))  
  19.         {  
  20.             if(c == 0)  
  21.             {  
  22.                 s1 = token;  
  23.                 c++;  
  24.             }  
  25.             else  
  26.             {  
  27.                 s2 = token;  
  28.             }  
  29.         }  
  30.         int count1[26];  
  31.         int count2[26];  
  32.         for(int i = 0;i < 26;i++)  
  33.         {  
  34.             count1[i] = 0;  
  35.             count2[i] = 0;  
  36.         }  
  37.         for(int i = 0;i < s1.size();i++)  
  38.         {  
  39.             if(s1[i] != ' ')  
  40.                 count1[(char)tolower(s1[i])-97]++;  
  41.         }  
  42.         for(int i = 0;i < s2.size();i++)  
  43.         {  
  44.             if(s2[i] != ' ')  
  45.                 count2[(char)tolower(s2[i])-97]++;  
  46.         }  
  47.   
  48.         bool equal = true;  
  49.         for(int i = 0;i < 26;i++)  
  50.         {  
  51.             if(count1[i] != count2[i])  
  52.                 equal = false;  
  53.         }  
  54.         if(equal)  
  55.             cout << "true" << endl;  
  56.         else  
  57.             cout << "false" << endl;  
  58.     }  
  59.     return 0;  
  60. }  

沒有留言:

張貼留言