0

我在使用 C++ 进行字符串操作时遇到问题。

规则:如果句子或段落中重复相同的“单词”,我希望它变成一个整数。

例子:

  • 输入:we prefer questions that can be answered, not just we discussed that.
  • 输出:1 prefer questions 2 can be answered, not just 1 discussed 2.
1 we
2 that
4

3 回答 3

4

如果您使用关联数组来跟踪您已经看过的单词,这种类型的问题通常更容易解决。尝试使用STL 映射来存储您已经看过的单词。正确设置逻辑需要一些工作,但地图肯定会帮助您尝试做的事情。

于 2009-06-04T03:07:44.100 回答
4

这是我将采取的方法(仅限算法,因为它是家庭作业)。

  1. 创建一个将单词映射到计数的数据结构。
  2. 一次处理一个单词。
    • 如果是新词,则将其添加到数据结构中并将其计数设置为 1。
    • 如果它是现有的,只需增加计数。
  3. 处理完所有单词后,遍历数据结构中的每个单词,给计数大于 1 的单词一个唯一的整数。
  4. 创建一个新的文本字符串,以空开头,然后再次逐字处理文本。
    • 如果单词的计数为 1,则将该单词附加到新字符串中。
    • 如果计数大于一,则附加唯一整数。
于 2009-06-04T03:14:00.717 回答
1

解析:

   For each word in the string
          Check whether the word exists in map<WORD,Counter>
          if the WORD is new the insert into the map with counter =0
          otherwise increment the counter associated with word.

输出:(创建新句子)

For each word in the string
      Lookup into the vector for counter value
      if counter ==0 then insert WORD as it is
      otherwise convert the counter to string and insert 
于 2009-06-04T03:23:37.203 回答