Skip to content

Commit 2e60182

Browse files
authored
Create minimum-insertion-steps-to-make-a-string-palindrome.cpp
1 parent c2998fe commit 2e60182

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int minInsertions(string s) {
7+
const string reversed_s(s.crbegin(), s.crend());
8+
return s.length() - longestCommonSubsequence(s, reversed_s);
9+
}
10+
11+
private:
12+
int longestCommonSubsequence(const string& text1, const string& text2) {
13+
if (text1.length() < text2.length()) {
14+
return longestCommonSubsequence(text2, text1);
15+
}
16+
vector<vector<int>> dp(2, vector<int>(text2.length() + 1));
17+
for (int i = 1; i <= text1.length(); ++i) {
18+
for (int j = 1; j <= text2.length(); ++j) {
19+
dp[i % 2][j] = (text1[i - 1] == text2[j - 1])
20+
? dp[(i - 1) % 2][j - 1] + 1
21+
: max(dp[(i - 1) % 2][j], dp[i % 2][j - 1]);
22+
23+
}
24+
}
25+
return dp[text1.length() % 2][text2.length()];
26+
}
27+
};

0 commit comments

Comments
 (0)