Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ecaf278

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 84dd3f8 commit ecaf278

File tree

4 files changed

+66
-0
lines changed

4 files changed

+66
-0
lines changed

‎0516_longest_palindromic_subsequence/lps.c‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include <stdio.h>
22
#include <stdlib.h>
3+
#include <string.h>
34

45

56
static inline int max(int a, int b)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O1 -o test insertion.c
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
5+
6+
static inline int min(int a, int b)
7+
{
8+
return a < b ? a : b;
9+
}
10+
11+
int minInsertions(char * s){
12+
int i, j, len = strlen(s);
13+
int *dp = malloc(len * sizeof(int));
14+
memset(dp, 0, len * sizeof(int));
15+
for (i = len - 2; i >= 0; i--) {
16+
int left_down = 0;
17+
for (j = i + 1; j < len; j++) {
18+
int down = dp[j];
19+
if (s[i] == s[j]) {
20+
dp[j] = left_down;
21+
} else {
22+
dp[j] = min(down, dp[j - 1]) + 1;
23+
}
24+
left_down = down;
25+
}
26+
}
27+
return dp[len - 1];
28+
}
29+
30+
int main(int argc, char **argv)
31+
{
32+
if (argc != 2) {
33+
fprintf(stderr, "Usage: ./test s\n");
34+
exit(-1);
35+
}
36+
37+
printf("%d\n", minInsertions(argv[1]));
38+
return 0;
39+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
int minInsertions(string s) {
8+
int len = s.length();
9+
vector<int> dp(len);
10+
for (int i = len - 2; i >= 0; i--) {
11+
int left_down = 0;
12+
for (int j = i + 1; j < len; j++) {
13+
int down = dp[j];
14+
if (s[i] == s[j]) {
15+
dp[j] = left_down;
16+
} else {
17+
dp[j] = min(down, dp[j - 1]) + 1;
18+
}
19+
left_down = down;
20+
}
21+
}
22+
return dp[len - 1];
23+
}
24+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /