Skip to content

Commit c27161e

Browse files
committed
leetcode 2/17/2014
1 parent c60596c commit c27161e

2 files changed

Lines changed: 79 additions & 0 deletions

File tree

‎LeetCode/minDistance.cpp‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <deque>
4+
#include <algorithm>
5+
using namespace std;
6+
7+
#define REP(i,n) for(int i=0;i<(n);++i)
8+
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
9+
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
10+
11+
string w1, w2;
12+
int n1, n2;
13+
vector<vector<int> > mm;
14+
15+
int dp(int i1, int i2) {
16+
int& res = mm[i1][i2];
17+
if (res != -1) return res;
18+
19+
if (i1 == n1) return res = n2 - i2;
20+
if (i2 == n2) return res = n1 - i1;
21+
22+
if (w1[i1] == w2[i2]) return res = dp(i1 + 1, i2 + 1);
23+
24+
res = 1 + dp(i1 + 1, i2 + 1);
25+
res = min(res, 1 + dp(i1, i2 + 1));
26+
res = min(res, 1 + dp(i1 + 1, i2));
27+
28+
return res;
29+
}
30+
31+
class Solution {
32+
public:
33+
int minDistance(string word1, string word2) {
34+
w1 = word1, w2 = word2;
35+
if (w1.length() > w2.length()) swap(w1, w2);
36+
n1 = w1.length(), n2 = w2.length();
37+
if (n1 == 0) return n2;
38+
mm.assign(n1 + 5, vector<int>(n2 + 5, -1));
39+
return dp(0, 0);
40+
}
41+
};
42+
43+
int main() {
44+
Solution s;
45+
cout << s.minDistance("acde", "abcd") << endl;
46+
return 0;
47+
}

‎LeetCode/sortColors.cpp‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <deque>
4+
#include <algorithm>
5+
using namespace std;
6+
7+
#define REP(i,n) for(int i=0;i<(n);++i)
8+
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
9+
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
10+
11+
class Solution {
12+
public:
13+
void sortColors(int A[], int n) {
14+
if (n <= 1) return;
15+
16+
int lt = 0, rt = n - 1;
17+
while (A[lt] == 0) ++lt;
18+
while (A[rt] == 2) --rt;
19+
FOR(i,lt,rt) {
20+
if (A[i] == 0) swap(A[lt++], A[i]);
21+
if (A[i] == 2) swap(A[rt--], A[i--]);
22+
}
23+
}
24+
};
25+
26+
int main() {
27+
int A[] = {2, 1, 0, 2, 0, 1, 1, 1, 0, 2, 2, 0, 2, 1, 0};
28+
Solution s;
29+
s.sortColors(A, 15);
30+
REP(i,15) cout << A[i] << endl;
31+
return 0;
32+
}

0 commit comments

Comments
 (0)