


Rearrange the characters of a string to form a valid English numeric representation
In this problem, we need to rearrange the characters of the given string to get a valid English numeric representation. The first approach could be to find all permutations of the string, extract English words related to numbers, and convert them into numbers.
Another way to solve this problem is to find a unique character from each word. In this tutorial, we will learn two ways to solve a given problem.
Problem Statement- We are given a string of length N containing lowercase characters. The string contains English word representations of numbers [0-9] in random order. We need to extract English words from string, convert them to numbers and display these numbers in ascending order
Example Example
Input – str = "zeoroenwot"
Output –‘012’
Explanation– We can extract 'zero', 'one' and 'two' from the given string and then sort them in increasing numerical order.
Input – str = ‘zoertowxisesevn’
Output –‘0267’
Explanation – We can extract "zero", "two", "six" and "seven" from the given string.
method one
In this method, we will use the next_permutation() method to get the permutation of the string. We will then extract number-related English words from each permutation and keep track of the maximum total number of words extracted from any permutation. From this we will form the string.
algorithm
Define the countOccurrences() function, which accepts strings and words as parameters. It is used to count the number of occurrences of a specific word in a given string.
Define the variable 'count' and initialize it to zero.
Use a while loop to traverse the string. If we find the word at the current position, the value of 'count' is increased by 1 and the value of 'pos' is skipped by the length of the word.
Return the value of ‘count’
convertToDigits() function is used to convert words into numbers
Define a vector named 'words', which contains the English representation of the number. Also, define ‘max_digits’ to store the maximum number of words in any permutation of the string. Furthermore, define the 'digit_freq' map to store the frequency of each digit when we can extract the maximum word from any permutation.
Use the sort() method to sort the given string.
Use next_permutations() method with do-while() loop. Within the loop, use another loop to iterate over the word vectors.
Count the number of occurrences of each word in the current permutation and update the 'word_freq' map based on this. At the same time, add the resulting value to the 'cnt' variable.
If the value of 'cnt' is greater than 'max_digits', update the values of 'max_digits' and 'digit_frequancy'.
Traverse the "digit_freq" map and convert numbers to strings.
Example
#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); }
Output
The string after converting to digits and sorting them in non-decreasing order is 012
Time complexity - O(N*N!), because we need to find all permutations.
Space complexity - O(N) for storing the final string.
Method Two
This method is an optimized version of the above method. Here we will take a unique character from each word and find the exact word from the given string based on this character.
observe
We have 'z' unique ones in 'zero'.
We have 'w' uniques in 'two'.
We have 'u' unique ones in 'four'.
We have 'x' unique ones out of 'six'.
We have 'gg' unique ones in 'eight'.
We can extract all unique words containing "h" from "three", just like we considered above.
We can take out the only "o" from "one" because we have considered all words containing "o".
We can select ‘f’ from ‘five’ as all words containing ‘f’ as above.
We have 'v' unique ones in 'seven'.
We can take the ‘i’ from ‘nine’ as all the words containing ‘i’ that we considered above.
algorithm
Define the 'words' vector containing English words and make sure to follow the example order below as we have considered unique words accordingly. Also, define a vector of unique characters and their numeric representation
Count the frequency of each character and store it in the map.
Traverse the array of unique characters
If the map contains a currently unique character, store its frequency value in the 'cnt' variable.
Now, iterate through the current word. Decrease the frequency of each character of a word by 'cnt' in the map.
在‘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),用于存储最终的字符串。
The above is the detailed content of Rearrange the characters of a string to form a valid English numeric representation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

C Learners and developers can get resources and support from StackOverflow, Reddit's r/cpp community, Coursera and edX courses, open source projects on GitHub, professional consulting services, and CppCon. 1. StackOverflow provides answers to technical questions; 2. Reddit's r/cpp community shares the latest news; 3. Coursera and edX provide formal C courses; 4. Open source projects on GitHub such as LLVM and Boost improve skills; 5. Professional consulting services such as JetBrains and Perforce provide technical support; 6. CppCon and other conferences help careers

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

C still has important relevance in modern programming. 1) High performance and direct hardware operation capabilities make it the first choice in the fields of game development, embedded systems and high-performance computing. 2) Rich programming paradigms and modern features such as smart pointers and template programming enhance its flexibility and efficiency. Although the learning curve is steep, its powerful capabilities make it still important in today's programming ecosystem.

The future of C will focus on parallel computing, security, modularization and AI/machine learning: 1) Parallel computing will be enhanced through features such as coroutines; 2) Security will be improved through stricter type checking and memory management mechanisms; 3) Modulation will simplify code organization and compilation; 4) AI and machine learning will prompt C to adapt to new needs, such as numerical computing and GPU programming support.

The application of static analysis in C mainly includes discovering memory management problems, checking code logic errors, and improving code security. 1) Static analysis can identify problems such as memory leaks, double releases, and uninitialized pointers. 2) It can detect unused variables, dead code and logical contradictions. 3) Static analysis tools such as Coverity can detect buffer overflow, integer overflow and unsafe API calls to improve code security.

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron
