Anagrams by Stack

本文介绍了一种通过栈的推入(Push)和弹出(Pop)操作来生成两个单词间字谜(anagram)的方法。具体实现中,针对每一对输入的单词,程序将输出一系列有效的栈操作序列,这些序列能够将源单词转换为目标单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Anagrams by Stack

Time limit: 1 Seconds   Memory limit: 32768K  
Total Submit: 1719   Accepted Submit: 724  

How can anagrams result from sequences of stack operations? There are two sequences of stack operators which can convert TROT to TORT:

[
i i i i o o o o
i o i i o o i o
]

where i stands for Push and o stands for Pop. Your program should, given pairs of words produce sequences of stack operations which convert the first word to the second.

Input

The input will consist of several lines of input. The first line of each pair of input lines is to be considered as a source word (which does not include the end-of-line character). The second line (again, not including the end-of-line character) of each pair is a target word. The end of input is marked by end of file.

Output

For each input pair, your program should produce a sorted list of valid sequences of i and o which produce the target word from the source word. Each list should be delimited by

[
]
and the sequences should be printed in "dictionary order". Within each sequence, each i and o is followed by a single space and each sequence is terminated by a new line.
Process

A stack is a data storage and retrieval structure permitting two operations:

Push - to insert an item and
Pop - to retrieve the most recently pushed item

We will use the symbol i (in) for push and o (out) for pop operations for an initially empty stack of characters. Given an input word, some sequences of push and pop operations are valid in that every character of the word is both pushed and popped, and furthermore, no attempt is ever made to pop the empty stack. For example, if the word FOO is input, then the sequence:

i i o i o ois valid, but
i i o is not (it's too short), neither is
i i o o o i(there's an illegal pop of an empty stack)

Valid sequences yield rearrangements of the letters in an input word. For example, the input word FOO and the sequence i i o i o o produce the anagram OOF. So also would the sequence i i i o o o. You are to write a program to input pairs of words and output all the valid sequences of i and o which will produce the second member of each pair from the first.

Sample Input
madam
adamm
bahama
bahama
long
short
eric
rice
Sample Output
[
i i i i o o o i o o
i i i i o o o o i o
i i o i o i o i o o
i i o i o i o o i o
]
[
i o i i i o o i i o o o
i o i i i o o o i o i o
i o i o i o i i i o o o
i o i o i o i o i o i o
]
[
]
[
i i o i o i o o
]
My Solution
#include <iostream>
#include <string>
#include <set>
#include <vector>
//#include <fstream>

using namespace std;

void findAllPaths(const string& source, unsigned int from, const string& target, unsigned int to, vector<char> stack, string actions, set<string>& paths) {
  if (from < source.length()) {
    stack.push_back(source.at(from++));
    actions.append("i ");
    findAllPaths(source, from, target, to, stack, actions, paths);
  }
 
  while (stack.size() > 0 && to < target.length() && stack[stack.size() - 1] == target.at(to)) {
    stack.pop_back();
    actions.append("o ");
    ++to;
    findAllPaths(source, from, target, to, stack, actions, paths);
  }
 
  if (from == source.length() && to == target.length() && stack.size() == 0 && actions.length() > 0) {
    actions.push_back('/n');
    paths.insert(actions);
  } 
}

int main() {
  string source, target;
 
  //fstream infile("in.txt");
  //cin.rdbuf(infile.rdbuf());
 
  while (cin >> source >> target) { 
    string actions;
    set<string> paths;
    vector<char> stack;
    unsigned int from = 0, to = 0;
   
    findAllPaths(source, from, target, to, stack, actions, paths);
   
    set<string>::iterator pos;
    cout << "[" << endl;
    for (pos = paths.begin(); pos != paths.end(); ++pos) {
      cout << *pos;
    }
    cout << "]" << endl;
  }
 
  //infile.close();
}

=====================================
Problem Source: Zhejiang University Local Contest 2001
### 关于 `Group Anagrams` 的实现方法 #### 方法一:基于排序的哈希表 对于每一个字符串,先将其字符按照字典顺序排列得到一个新的字符串作为键值存入哈希表中。由于字母异位词经过这样的处理后会产生相同的键值,因此可以将具有相同键值的所有原始字符串收集起来形成最终的结果集[^1]。 ```cpp vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> mp; for (string& str : strs) { string key = str; sort(key.begin(), key.end()); mp[key].push_back(str); } vector<vector<string>> ans; for (auto it = mp.begin(); it != mp.end(); ++it) { ans.push_back(it->second); } return ans; } ``` 这种方法的时间复杂度主要取决于排序操作以及遍历输入列表的操作。如果n表示输入列表长度,k代表最长单词长度,则时间复杂度大约为O(n * k log k)。 #### 方法二:基于计数数组的哈希表 考虑到ASCII码范围内的字符数量有限(共26个小写字母),可以直接利用固定大小(26)的整型数组记录每个字符串内各个字符出现次数的情况,并以此构建唯一的key用于存储到hashmap当中去。这种方式避免了显式的字符串排序过程,在某些情况下可能会更高效一些。 ```cpp vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> mp; for (const auto& s : strs){ array<int, 26> counts{}; for(const char c:s){ counts[c-'a']++; } // 将counts转换成可作为key使用的字符串形式 string key = ""; for(auto count:counts){ key += "#"+to_string(count); } mp[key].emplace_back(s); } vector<vector<string>> res; for(auto& p:mp){ res.emplace_back(p.second); } return res; } ``` 此版本通过使用定长的频率分布向量代替直接对字符串进行排序的方式减少了不必要的计算开销,理论上能够提供更好的性能表现。 #### 方法三:质数相乘法 另一种巧妙的做法是给每个不同的字母分配一个独一无二的小质数值,之后把整个字符串看作是由这些质因数构成的大合数;这样只要两个串对应的积相等就说明它们互为变位词。不过这种思路虽然新颖有趣但在实际应用时效率未必占优,因为涉及到大数运算等问题。 ```cpp // 这里仅给出概念性的伪代码示意而非完整的解决方案 unordered_map<long long,vector<string>> map; for each word w do{ product=1; foreach character ch in w do{ product *= primes[ch]; //假设primes[]已经预先定义好并初始化完毕 } map[product].add(w); } return convert(map.values()); // 把map里的value部分转成题目要求的形式返回 ``` 上述三种方式各有特点,可以根据具体场景和个人偏好选择合适的一种来解决问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值