Program to count number of palindromes after minimum number of split of the string in C++

C++Server Side ProgrammingProgramming

Suppose we have a lowercase string s, we have to split it into as few strings as possible such that each string is a palindrome and then find the number of strings.

So, if the input is like s = "levelracecar", then the output will be 2, as there are two palindromes "level" and "racecar".

To solve this, we will follow these steps −

  • n := size of A

  • Define an array result of size (n + 1)

  • result[n] := -1

  • for initialize i := n - 1, when i >= 0, update (decrease i by 1), do −

    • result[i] := n - i - 1

    • for initialize j := i, when j < n, update (increase j by 1), do −

      • if substring of A from range i to j - i is palindrome, then −

        • result[i] := minimum of result[i] and 1 + result[j + 1]

  • return result[0] + 1

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool isPalindrome(string A) {
      int left = 0;
      int right = A.size() - 1;
      while (left < right) {
         if (A[left] != A[right]) {
            return 0;
         }
         left++;
         right--;
      }
      return 1;
   }
   int solve(string A) {
      int n = A.size();
      vector<int> result(n + 1);
      result[n] = -1;
      for (int i = n - 1; i >= 0; i--) {
         result[i] = n - i - 1;
         for (int j = i; j < n; j++) {
            if (isPalindrome(A.substr(i, j - i + 1))) {
               result[i] = min(result[i], 1 + result[j + 1]);
            }
         }
      }
      return result[0] + 1;
   }
};
int solve(string s) {
   return (new Solution())->solve(s);
}
int main(){
   string s = "levelracecar";
   cout << solve(s);
}

Input

"levelracecar"

Output

2
raja
Published on 23-Dec-2020 06:18:12
Advertisements