目录
示例例子
方法一
算法
示例
输出
方法二
观察
首页 后端开发 C++ 重新排列字符串的字符,以形成有效的英文数字表示形式

重新排列字符串的字符,以形成有效的英文数字表示形式

Sep 24, 2023 pm 05:21 PM
重新排列字符 英文数字表示 有效表示形式

重新排列字符串的字符,以形成有效的英文数字表示形式

在这个问题中,我们需要重新排列给定字符串的字符,以获得有效的英文数字表示。第一种方法可以是找到字符串的所有排列,提取与数字相关的英文单词,并将它们转换为数字。

另一种解决该问题的方法是从每个单词中找到一个唯一的字符。在本教程中,我们将学习解决给定问题的两种方法。

问题陈述- 我们给出了一个包含小写字符且长度为N的字符串。该字符串以随机顺序包含了[0-9]数字的英文单词表示。我们需要从字符串中提取英文单词,将它们转换为数字,并按升序显示这些数字

示例例子

输入 – str = "zeoroenwot"

输出 – ‘012’

解释– 我们可以从给定的字符串中提取出'zero'、'one'和'two',然后按照数字的增序进行排序。

输入 – str = ‘zoertowxisesevn’

输出 – ‘0267’

Explanation – 我们可以从给定的字符串中提取出“zero”、“two”、“six”和“seven”。

方法一

在这种方法中,我们将使用next_permutation()方法来获取字符串的排列。然后,我们将从每个排列中提取与数字相关的英文单词,并跟踪从任何排列中提取的最大单词总数。根据这一点,我们将形成字符串。

算法

  • 定义countOccurrences()函数,它接受字符串和单词作为参数。它用于计算给定字符串中特定单词的出现次数。

    • 定义变量‘count’,并将其初始化为零。

    • 使用while循环遍历字符串。如果我们在当前位置找到了该单词,则将'count'的值增加1,并将'pos'的值跳过单词的长度。

    • 返回‘count’的值

  • convertToDigits() 函数用于将单词转换为数字

  • 定义名为‘words’的向量,其中包含数字的英文表示。同时,定义‘max_digits’来存储字符串的任意排列中的最大单词数。此外,定义‘digit_freq’映射来存储当我们可以从任意排列中提取最大单词时,每个数字的频率。

  • 使用sort()方法对给定的字符串进行排序。

  • 使用 next_permutations() 方法与 do-while() 循环。在循环中,使用另一个循环来迭代单词向量。

  • 计算当前排列中每个单词的出现次数,并根据此更新'word_freq'映射。同时,将结果值添加到'cnt'变量中。

  • 如果‘cnt’的值大于‘max_digits’,则更新‘max_digits’和‘digit_frequancy’的值。

  • 遍历“digit_freq”映射并将数字转换为字符串。

示例

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

//  function to count the total number of occurrences of a word in a string
int countOccurrences(const string &text, const string &word){
   int count = 0;
   size_t pos = 0;
   while ((pos = text.find(word, pos)) != std::string::npos){
      count++;
      pos += word.length();
   }
   return count;
}
string convertToDigits(string str){
   // defining the words vector
   vector<string> words = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
   int max_digits = 0;
   map<int, int> digit_freq;
   // Traverse the permutations vector
   sort(str.begin(), str.end()); // Sort the string in non-decreasing order
   do{
      string temp = str;
      int cnt = 0;
      map<int, int> word_freq;
      // Traverse the words vector
      for (int j = 0; j < words.size(); j++){
         string temp_word = words[j];
         // finding the number of occurrences of the word in the permutation
         int total_temp_words = countOccurrences(temp, temp_word);
         // storing the number of occurrences of the word in the map
         word_freq[j] = total_temp_words;
         cnt += total_temp_words;
     }
     // If the total number of digits in the permutation is greater than the max_digits, update the max_digits and digit_freq
     if (cnt > max_digits){
         max_digits = cnt;
         digit_freq = word_freq;
      }
   } while (next_permutation(str.begin(), str.end()));
   string res = "";
   // Traverse the digit_freq map
   for (auto it = digit_freq.begin(); it != digit_freq.end(); it++){
      int digit = it->first;
      int freq = it->second;
      // Append the digit to the result string
      for (int i = 0; i < freq; i++){
         res += to_string(digit);
      }
   }
   return res;
}
int main(){
   string str = "zeoroenwot";
   // Function Call
   cout << "The string after converting to digits and sorting them in non-decreasing order is " << convertToDigits(str);
}
登录后复制

输出

The string after converting to digits and sorting them in non-decreasing order is 012
登录后复制

时间复杂度 - O(N*N!),因为我们需要找到所有的排列。

空间复杂度 - O(N),用于存储最终的字符串。

方法二

这种方法是上述方法的优化版本。在这里,我们将从每个单词中取一个唯一的字符,并根据这个字符从给定的字符串中找到确切的单词。

观察

  • 我们在‘zero’中有‘z’个独特的。

  • 我们在‘two’中有‘w’个唯一的。

  • 我们在'four'中有'u'个独特的。

  • 我们在‘六’中有‘x’个独特的。

  • 我们在‘eight’中有‘gg’个独特的。

  • 我们可以从“three”中提取出包含“h”的所有唯一单词,就像我们上面考虑的那样。

  • 我们可以从“one”中取出唯一的“o”,因为我们已经考虑了所有包含“o”的单词。

  • 我们可以从“five”中选择‘f’作为所有包含‘f’的单词,如上所述。

  • 我们在“seven”中有‘v’个独特的。

  • 我们可以从“nine”中取出‘i’作为我们上面考虑过的所有包含‘i’的单词。

算法

  • 定义包含英语单词的'words'向量,并确保按照下面的示例顺序进行,因为我们已经相应地考虑了唯一的单词。同时,定义一个唯一字符的向量及其数字表示

  • 统计每个字符的频率并将其存储在映射中。

  • 遍历唯一字符的数组

  • 如果地图中包含当前唯一的字符,则将其频率值存储在'cnt'变量中。

  • 现在,遍历当前单词。在地图中将单词的每个字符的频率减少'cnt'。

  • 在‘digits’向量中添加一个单词,重复‘cnt’次。

  • 对数字字符串进行排序,并从函数中返回。

示例

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;

string convertToDigits(string str){
   // store the words corresponding to digits
   vector<string> words = { "zero", "two", "four", "six", "eight", "three", "one", "five", "seven", "nine" };
   // store the unique characters of the words
   vector<char> unique_chars = {'z',  'w', 'u', 'x', 'g', 'h', 'o', 'f', 'v', 'i'};
   // store the digits corresponding to the words
   vector<int> numeric = {0, 2, 4, 6, 8, 3, 1, 5, 7, 9};
   // to store the answer
   vector<int> digits = {};
   // unordered map to store the frequency of characters
   unordered_map<char, int> freq;
   // count the frequency of each character
   for (int i = 0; i < str.length(); i++){
      freq[str[i]]++;
   }
   // Iterate over the unique characters
   for (int i = 0; i < unique_chars.size(); i++){
      // store the count of the current unique character
      int cnt = 0;
      // If the current unique character is present, store its count. Otherwise, it will be 0.
      if (freq[unique_chars[i]] != 0)
          cnt = freq[unique_chars[i]];
      // Iterate over the characters of the current word
      for (int j = 0; j < words[i].length(); j++){
          // Reduce the frequency of the current character by cnt times in the map
          if (freq[words[i][j]] != 0)
             freq[words[i][j]] -= cnt;
      }
      // Push the current digit cnt times in the answer
      for (int j = 0; j < cnt; j++)
         digits.push_back(numeric[i]);
   }
   // sort the digits in non-decreasing order
   sort(digits.begin(), digits.end());
   string finalStr = "";
   // store the answer in a string
   for (int i = 0; i < digits.size(); i++)
     finalStr += to_string(digits[i]);      
   return finalStr;
}
int main(){
   string str = "zoertowxisesevn";
   // Function Call
   cout << "The string after converting to digits and sorting them in non-decreasing order is " << convertToDigits(str);
}
登录后复制

输出

The string after converting to digits and sorting them in non-decreasing order is 0267
登录后复制

时间复杂度 - O(N),其中N是字符串的长度。

空间复杂度 - O(N),用于存储最终的字符串。

以上是重新排列字符串的字符,以形成有效的英文数字表示形式的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

C语言数据结构:树和图的数据表示与操作 C语言数据结构:树和图的数据表示与操作 Apr 04, 2025 am 11:18 AM

C语言数据结构:树和图的数据表示与操作树是一个层次结构的数据结构由节点组成,每个节点包含一个数据元素和指向其子节点的指针二叉树是一种特殊类型的树,其中每个节点最多有两个子节点数据表示structTreeNode{intdata;structTreeNode*left;structTreeNode*right;};操作创建树遍历树(先序、中序、后序)搜索树插入节点删除节点图是一个集合的数据结构,其中的元素是顶点,它们通过边连接在一起边可以是带权或无权的数据表示邻

C语言文件操作难题的幕后真相 C语言文件操作难题的幕后真相 Apr 04, 2025 am 11:24 AM

文件操作难题的真相:文件打开失败:权限不足、路径错误、文件被占用。数据写入失败:缓冲区已满、文件不可写、磁盘空间不足。其他常见问题:文件遍历缓慢、文本文件编码不正确、二进制文件读取错误。

c语言函数的基本要求有哪些 c语言函数的基本要求有哪些 Apr 03, 2025 pm 10:06 PM

C语言函数是代码模块化和程序搭建的基础。它们由声明(函数头)和定义(函数体)组成。C语言默认使用值传递参数,但也可使用地址传递修改外部变量。函数可以有返回值或无返回值,返回值类型必须与声明一致。函数命名应清晰易懂,使用驼峰或下划线命名法。遵循单一职责原则,保持函数简洁性,以提高可维护性和可读性。

c上标3下标5怎么算 c上标3下标5算法教程 c上标3下标5怎么算 c上标3下标5算法教程 Apr 03, 2025 pm 10:33 PM

C35 的计算本质上是组合数学,代表从 5 个元素中选择 3 个的组合数,其计算公式为 C53 = 5! / (3! * 2!),可通过循环避免直接计算阶乘以提高效率和避免溢出。另外,理解组合的本质和掌握高效的计算方法对于解决概率统计、密码学、算法设计等领域的许多问题至关重要。

c语言函数名定义 c语言函数名定义 Apr 03, 2025 pm 10:03 PM

C语言函数名定义包括:返回值类型、函数名、参数列表和函数体。函数名应清晰、简洁、统一风格,避免与关键字冲突。函数名具有作用域,可在声明后使用。函数指针允许将函数作为参数传递或赋值。常见错误包括命名冲突、参数类型不匹配和未声明的函数。性能优化重点在函数设计和实现上,而清晰、易读的代码至关重要。

C语言多线程编程:新手指南与疑难解答 C语言多线程编程:新手指南与疑难解答 Apr 04, 2025 am 10:15 AM

C语言多线程编程指南:创建线程:使用pthread_create()函数,指定线程ID、属性和线程函数。线程同步:通过互斥锁、信号量和条件变量防止数据竞争。实战案例:使用多线程计算斐波那契数,将任务分配给多个线程并同步结果。疑难解答:解决程序崩溃、线程停止响应和性能瓶颈等问题。

c语言函数的概念 c语言函数的概念 Apr 03, 2025 pm 10:09 PM

C语言函数是可重复利用的代码块,它接收输入,执行操作,返回结果,可将代码模块化提高可复用性,降低复杂度。函数内部机制包含参数传递、函数执行、返回值,整个过程涉及优化如函数内联。编写好的函数遵循单一职责原则、参数数量少、命名规范、错误处理。指针与函数结合能实现更强大的功能,如修改外部变量值。函数指针将函数作为参数传递或存储地址,用于实现动态调用函数。理解函数特性和技巧是编写高效、可维护、易理解的C语言程序的关键。

c语言如何输出倒数 c语言如何输出倒数 Apr 04, 2025 am 08:54 AM

如何在 C 语言中输出倒数?回答:使用循环语句。步骤:1. 定义变量 n 存储要输出的倒数数字;2. 使用 while 循环持续打印 n 直到 n 小于 1;3. 在循环体内,打印出 n 的值;4. 在循环末尾,将 n 减去 1 以输出下一个更小的倒数。

See all articles