Table of Contents
Problem Statement
Example
enter
Output
illustrate
method 1
algorithm
in conclusion
Home Backend Development C++ Modify the sentence by reversing the order in which all palindromic words appear

Modify the sentence by reversing the order in which all palindromic words appear

Aug 27, 2023 am 10:01 AM
Revise reverse palindrome

Modify the sentence by reversing the order in which all palindromic words appear

Problem Statement

We are given a string str, containing a total of N words. We need to find all palindrome words in a given string and create a new string by reversing the order of all palindrome words.

Example

enter

str = ‘nayan was gone to navjivan eye hospital’
Copy after login

Output

‘eye was gone to navjivan nayan hospital’
Copy after login

illustrate

The string contains three palindromes: nayan, navjivan and eye. We reversed the order of all three words and kept all other words the same.

enter

‘Hello, users! How are you?’
Copy after login
Copy after login

Output

‘Hello, users! How are you?’
Copy after login
Copy after login

illustrate

It gives the same output since the string does not contain any palindrome words.

enter

‘Your eye is beautiful.’
Copy after login
Copy after login

Output

‘Your eye is beautiful.’
Copy after login
Copy after login

illustrate

It gives the same output as a string containing only a single palindrome word.

method 1

In this method, we first split the string into words. After that, we will filter all palindrome words. Next, we reverse the order of all palindromes.

Finally, we iterate through the string and if the current word is a palindrome word, we replace it with another palindrome word in reverse order.

algorithm

  • Step 1 - Execute the reversePlaindromic() function by passing a string as argument that returns the result string.

  • Step 2 - Create isPalindrome() function to check if a word is a palindrome.

  • Step 2.1 - Initialize "start" to 0 and "end" to string length – 1.

  • Step 2.2 - Use a while loop to iterate through the string, comparing the first and last characters, comparing the second and penultimate characters, and so on. If any characters do not match, false is returned because it is not a palindrome string.

  • Step 2.3 - Returns true if the string is a palindrome.

  • Step 3 - Create a vector to store the words of the string. Additionally, define the "temp" variable to store the word.

  • Step 4 - Use a for loop to iterate over the string and append the character to the temporary value if it is not equal to a space (‘ ’). Otherwise, push the value of temp to the allWords vector.

  • Step 5 - Iterate over the allWords vector and check if the current word is a palindrome using the isPalindrome() function. If so, push the word into the "palindromWords" vector.

  • Step 6 - Invert the "palindromWords" list.

  • Step 7 - Now, iterate over the "allWords" vector again and check if the current word is a palindrome. If so, replace it with a respected word from the "palindromWords" list.

  • Step 8 - Iterate over the "palindromWords" list and create a string by appending all words to the result variable. Returns the result string.

Example

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to check if a string is a palindrome
bool isPalindrome(string str){
   int start = 0;
   int end = str.length() - 1;
   // iterate till start < end
   while (start < end){
      // check if the character at the start and end are not the same and return false, else increment start and decrement end
      if (str[start] != str[end]){
         return false;
      } else {
         start++;
         end--;
      }
   }
   return true;
}
string reversePalindromic(string str) {
   // vectors to store all words and palindromic words
   vector<string> palindromWords;
   vector<string> allWords;
   // variable to store single word
   string temp = "";
   for (char x : str) {
      // If the current character is not space, then append it to temp; else, add temp to palindrome words and make temp NULL
      if (x != ' ') {
         temp += x;
      } else {
         allWords.push_back(temp);
         temp = "";
      }
   }
   // push the last word to all words
   allWords.push_back(temp);
   // fetch all palindromic words
   for (string x : allWords){
      if (isPalindrome(x)){
         // Update newlist
         palindromWords.push_back(x);
      }
   }
   // Reverse the vector
   reverse(palindromWords.begin(), palindromWords.end());
   int k = 0;
   for (int i = 0; i < allWords.size(); i++){
      // If the current word is a palindrome, push it to palindrome words
      if (isPalindrome(allWords[i])){
         allWords[i] = palindromWords[k];
         k++;
      }
   }
   string result = "";
   for (string x : allWords) {
      result += x;
      result += " ";
   }
   return result;
}
int main(){
   string str = "nayan was gone to navjivan eye hospital";
   string reverse = reversePalindromic(str);
   cout << reverse << endl;
   return 0;
}
Copy after login

Output

eye was gone to navjivan nayan hospital
Copy after login
  • Time Complexity - O(N) since we iterate over strings of length N.

  • Space Complexity - O(K) because we use a list to store words, where k is the total number of words in the string.

in conclusion

We learned to take all the palindrome words from the sentence and add them in reverse order. In the above code, the programmer can try changing the implementation of the isPalindrome() function to learn something new.

The above is the detailed content of Modify the sentence by reversing the order in which all palindromic words appear. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to change the personal name in the group on DingTalk_How to modify the personal name in the group on DingTalk How to change the personal name in the group on DingTalk_How to modify the personal name in the group on DingTalk Mar 29, 2024 pm 08:41 PM

1. First open DingTalk. 2. Open the group chat and click the three dots in the upper right corner. 3. Find my nickname in this group. 4. Click to enter to modify and save.

How to Change User Folder Name: Win11 Tutorial How to Change User Folder Name: Win11 Tutorial Jan 09, 2024 am 10:34 AM

Some games will be automatically installed into the user folder and require an English folder. However, many friends do not know how to modify the user folder name in win11. In fact, we only need to modify the user name. Modify the user folder name in win11: The first step is to press the "Win+R" key combination on the keyboard. In the second step, enter "gpedit.msc" and press Enter to open the Group Policy Editor. Step 3: Expand "Security Settings" under "Windows Settings" Step 4: Open "Security Options" in "Local Policies" Step 5: Double-click to open the "Account: Rename System Administrator Account" policy on the right. Step 6: Enter the name of the folder you want to modify below and click "OK" to save. Modify user folder

Can Douyin Blue V change its name? What are the steps to change the name of corporate Douyin Blue V account? Can Douyin Blue V change its name? What are the steps to change the name of corporate Douyin Blue V account? Mar 22, 2024 pm 12:51 PM

Douyin Blue V certification is the official certification of a company or brand on the Douyin platform, which helps enhance brand image and credibility. With the adjustment of corporate development strategy or the update of brand image, the company may want to change the name of Douyin Blue V certification. So, can Douyin Blue V change its name? The answer is yes. This article will introduce in detail the steps to modify the name of the enterprise Douyin Blue V account. 1. Can Douyin Blue V change its name? You can change the name of Douyin Blue V account. According to Douyin’s official regulations, corporate Blue V certified accounts can apply to change their account names after meeting certain conditions. Generally speaking, enterprises need to provide relevant supporting materials, such as business licenses, organization code certificates, etc., to prove the legality and necessity of changing the name. 2. What are the steps to modify the name of corporate Douyin Blue V account?

Win11 power mode modification location and method Win11 power mode modification location and method Dec 30, 2023 pm 05:25 PM

In the win11 system, we can reduce our battery consumption or improve our system performance by modifying the power mode. The setting method is very simple, just find the power option. Let’s follow the editor to take a look at the specific operation process. How to modify the power mode in win11 1. First click the leftmost button on the taskbar to open the start menu. 2. Then search and open "Control Panel" above the Start menu. 3. In the Control Panel, you can find "Hardware and Sound" 4. Enter Hardware and Sound, click "Choose a power plan" under Power Options 5. Then in You can modify the power mode. You can select balanced, energy-saving mode or expand the hidden additional plan and select high-performance mode.

PyCharm background color adjustment tips: Master it quickly! PyCharm background color adjustment tips: Master it quickly! Feb 03, 2024 am 09:39 AM

To quickly master the skills of modifying the background color of PyCharm, you need specific code examples. In recent years, the Python language has become more and more popular in the field of program development, and PyCharm, as an integrated development environment (IDE), is loved and used by the majority of developers. In PyCharm, some developers often personalize the IDE interface, including changing the background color. This article will introduce the technique of modifying the background color of PyCharm and give specific code examples to help readers quickly master this skill.

Win10 sleep time modification tips revealed Win10 sleep time modification tips revealed Mar 08, 2024 pm 06:39 PM

Win10 Sleep Time Modification Tips Revealed As one of the currently widely used operating systems, Windows 10 has a sleep function to help users save power and protect the screen when not using the computer. However, sometimes the default sleep time does not meet the needs of users, so it is particularly important to know how to modify the Win10 sleep time. This article will reveal the tips for modifying the sleep time of Win10, allowing you to easily customize the system’s sleep settings. 1. Modify Win10 sleep time through “Settings” First, the simplest fix

Accelerate pip source and solve the problem of slow download speed Accelerate pip source and solve the problem of slow download speed Jan 17, 2024 am 10:18 AM

Quickly modify the pip source to solve the problem of slow download speed. Specific code examples are required. Introduction: During the development process of using Python, we often need to use pip to install various third-party libraries. However, due to network environment limitations or default source issues, pip download speeds are often very slow, which brings inconvenience to our development. Therefore, this article will introduce how to quickly modify the pip source to solve the problem of slow download speed, and provide specific code examples. 1. Problem Analysis When using pip to download third-party libraries, I

Guide to modifying win11 window corners to rounded corners Guide to modifying win11 window corners to rounded corners Dec 31, 2023 pm 08:35 PM

After updating the win11 system, many friends found that the win11 interface window adopts a new rounded corner design. But some people don’t like this rounded corner design and want to modify it to the previous interface, but they don’t know how to modify it. Let’s take a look below. How to modify rounded corners in win11 1. The rounded corner design of win11 is a built-in system setting that cannot be modified at present. 2. So if you don’t like using the rounded corner design of win11, you can wait for Microsoft to provide a modification method. 3. If you are really not used to it, you can also choose to return to the previous win10 system. 4. If you don’t know how to roll back, you can check out the tutorials provided on this site. 5. If you cannot go back using the tutorial above, you can still

See all articles