【问题标题】:To remove the Duplicates from the given string (without sorting it) [duplicate]从给定字符串中删除重复项(不对其进行排序)[重复]
【发布时间】:2021-11-19 22:27:58
【问题描述】:

问题是要求从字符串中删除重复项,我想出了一个删除重复项的解决方案,但为此,我对字符串进行了排序。 所以我想知道有没有一种方法可以在不对字符串进行排序的情况下从字符串中删除重复项。

Test Cases : 

"allcbcd" -> "alcbd"

我的代码(必须对字符串进行排序的代码):

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string removeDup(string s)
{
   if (s.length() == 0)
   {
       return "";
   }

   sort(s.begin(), s.end());
   char ch = s[0];
   string ans = removeDup(s.substr(1));

   if (ch == ans[0])
   {
       return ans;
   }

   return (ch + ans);
}

int main()
{
   cout << removeDup("allcbbcd") << endl;

   return 0;
}

【问题讨论】:

  • 我能想到几个简单的低效方法。它必须高效吗?
  • 我首先想到的是使用正则表达式。 Here is a SO solution utilizing regex.
  • 其实我想要一个高效的方法,但我也想知道解决这个问题的不同方法。 @Eljay
  • 请注意,因为您只需要 return 删除重复字符的字符串,您可以创建一个辅助字符串并从原始字符串中一个一个地复制字符,如只要他们以前没有见过。找出一种有效的方法来检查一个角色是否曾被看过是由读者决定的。

标签: c++ string algorithm loops recursion


【解决方案1】:

仅考虑 ASCII 值创建一个大小为 256 的布尔数组。

遍历字符串并检查数组中字符的 ASCII 索引值。如果它已经设置为 true,则忽略该字符。如果不是,则将该字符添加到结果字符串中,并将数组中的 ASCII 索引值设置为 true。

最后,打印结果字符串。

如果您想让它支持 UTF-8 字符,请使用映射而不是数组。

【讨论】:

    【解决方案2】:

    这是一种无需排序(或使用递归循环)的方法:

    #include <iostream>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    string removeDup(string s)
    {
       string::size_type index = 0;
       string::iterator end = s.end();
    
       while (index < s.size()) {
           end = remove(s.begin()+index+1, end, s[index]);
           ++index;
       } 
    
       s.erase(end, s.end());
       return s;
    }
    
    int main()
    {
       cout << removeDup("allcbbcd") << endl;
    
       return 0;
    }
    

    Online Demo

    【讨论】:

      猜你喜欢
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2014-11-05
      • 2014-04-03
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多