forked from MainakRepositor/500-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ca95100
commit cccf054
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// A Naive recursive program to find minimum | ||
// number insertions needed to make a string | ||
// palindrome | ||
#include<bits/stdc++.h> | ||
using namespace std; | ||
|
||
|
||
// Recursive function to find | ||
// minimum number of insertions | ||
int findMinInsertions(char str[], int l, int h) | ||
{ | ||
// Base Cases | ||
if (l > h) return INT_MAX; | ||
if (l == h) return 0; | ||
if (l == h - 1) return (str[l] == str[h])? 0 : 1; | ||
|
||
// Check if the first and last characters are | ||
// same. On the basis of the comparison result, | ||
// decide which subrpoblem(s) to call | ||
return (str[l] == str[h])? | ||
findMinInsertions(str, l + 1, h - 1): | ||
(min(findMinInsertions(str, l, h - 1), | ||
findMinInsertions(str, l + 1, h)) + 1); | ||
} | ||
|
||
// Driver code | ||
int main() | ||
{ | ||
char str[] = "geeks"; | ||
cout << findMinInsertions(str, 0, strlen(str) - 1); | ||
return 0; | ||
} |