【问题标题】:Replacing repeated words within a string with integers用整数替换字符串中的重复单词
【发布时间】:2009-06-04 02:53:02
【问题描述】:

我在使用 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

【问题讨论】:

  • 因此,如果我可以改写一下,您希望将所有重复单词的实例替换为该单词的数字替换。随后遇到的每个重复单词都会获得一个新的递增数字。听起来像是一种独特的压缩方案...
  • yupz...你能帮我解决一下吗? ^^ -对不起我的英语不好-
  • 只要你试一试,你就会从中受益……写一些代码!!!如果它不能按您的意愿工作,这里的很多人会很乐意在您调试时提供帮助。
  • 正如其他人所说,向我们展示您到目前为止所做的事情。我们将从那里帮助您。
  • @afterlife 对不起,但直到现在,我仍然找不到算法。我还是 c 或 c++ 的新手。

标签: c++ algorithm text-processing


【解决方案1】:

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

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

【讨论】:

  • 这是掌握新手程序员关键的一个:解决方案涉及数据的两次连续传递。仔细考虑你需要在第 1 阶段做什么,然后在第 2 阶段做什么。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    解析:

       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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 2020-11-09
      • 2018-05-07
      • 2021-08-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多