156 - Ananagrams

题意:
在一个单词集合中, 若一个单词能找到另一个单词与其包含相同的字母, 则称此单词是可以 rearranged 的(如SpOT 与 StOp, 比较时不区分大小写). 找出所有不能进行 rearranged 的单词并按字典序从小到大输出.

思路:
1. 对每一个单词, 都与其他单词进行比较, 看它是否为 rearranged; 若不是, 则记录下来, 最后排序进行输出.
2. 比较 rearranged 时, 按以下步骤:
(1). 若长度不同, 则肯定是不能 rearranged 的.
(2). 每找到一个相同的字母, 就在两个单词里都把此字母删掉, 若最后两个单词都为空, 则此两单词是 rearranged 的, 否则就是不能 rearranged 的.

要点:
1. transform 转大/小写.
2. sort 进行排序.
3. copy 进行输出.

题目:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=92

代码:

# include <iostream>
# include <string>
# include <cstdio>
# include <cstring>
# include <vector>
# include <algorithm>
# include <cctype>
# include <iterator>
# include <assert.h>
using namespace std;

// transform 转 大/小 写

// 比较两个 word 是互否为 rearranged
bool isRearranged(string word1, string word2) {
  if (word1.size() != word2.size()) 
    return false;

  // 比较时不区分大小写, 所以这里先统一转一下
  transform(word1.begin(), word1.end(), word1.begin(), ::tolower);
  transform(word2.begin(), word2.end(), word2.begin(), ::tolower);

  // 每次从两个 word 里删除一个相匹配的字符, 直至最后全为空
  while (!word1.empty()) {
    char c = word1[0];
    size_t pos = word2.find(c); 

    if (pos == string::npos) 
      return false;
    
    word1.erase(0, 1);
    word2.erase(pos, 1);
  }

  return true;
}


int main(int argc, char const *argv[])
{
  #ifndef ONLINE_JUDGE
    freopen("156_i.txt", "r", stdin);  
    freopen("156_o.txt", "w", stdout); 
  #endif
  
  string word;
  vector<string> words;

  while (true) {
    cin >> word;
    if (word == "#")
      break;

    words.push_back(word);
  }

  vector<string> ananagramsWords;
  for (int i=0; i<words.size(); i++) {
    bool isAnanagrams = true;

    for (int j=0; j<words.size(); j++) {
      if (i != j) {
        if (isRearranged(words[i], words[j])) {
          isAnanagrams = false;
          break;
        }
      }
    }

    if (isAnanagrams) {
      ananagramsWords.push_back(words[i]);
    }
  }

  sort(ananagramsWords.begin(), ananagramsWords.end(), less<string>());
  copy(ananagramsWords.begin(), ananagramsWords.end(), 
       ostream_iterator<string>(cout, "\n"));

  return 0;
}

环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE

你可能感兴趣的:(uva,156,Ananagrams)