Skip to content

Commit 4949d1d

Browse files
committed
leetcode 2/13/2014
1 parent 51b8e36 commit 4949d1d

2 files changed

Lines changed: 92 additions & 0 deletions

File tree

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

LeetCode/nextPermutation.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
#define REP(i,n) for(int i=0;i<(n);++i)
7+
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
8+
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
9+
10+
class Solution {
11+
public:
12+
void nextPermutation(vector<int> &num) {
13+
int n = num.size();
14+
int idx = n - 1;
15+
while (idx - 1 >= 0 && num[idx - 1] >= num[idx]) --idx;
16+
if (--idx <= -1) {
17+
reverse(num.begin(), num.end());
18+
return;
19+
}
20+
21+
int lt = idx + 1, rt = n - 1;
22+
while (lt <= rt) {
23+
int mt = (lt + rt) / 2;
24+
if (num[mt] <= num[idx]) {
25+
rt = mt - 1;
26+
} else {
27+
lt = mt + 1;
28+
}
29+
}
30+
31+
swap(num[idx], num[rt]);
32+
reverse(num.begin() + idx + 1, num.end());
33+
}
34+
};
35+
36+
void test(int mm[], int len) {
37+
vector<int> num;
38+
num.assign(mm, mm + len);
39+
Solution s;
40+
s.nextPermutation(num);
41+
REP(i,num.size()) cout << num[i] << " ";
42+
cout << endl;
43+
}
44+
45+
int main() {
46+
int mm1[3] = {1, 2, 3};
47+
test(mm1, sizeof(mm1) / sizeof(mm1[0]));
48+
49+
int mm2[] = {3, 2, 1};
50+
test(mm2, sizeof(mm2) / sizeof(mm2[0]));
51+
52+
int mm3[] = {1, 1, 5};
53+
test(mm3, sizeof(mm3) / sizeof(mm3[0]));
54+
55+
return 0;
56+
}

0 commit comments

Comments
 (0)