Skip to content

Commit

Permalink
add leetcode academicpages#5 and academicpages#6
Browse files Browse the repository at this point in the history
  • Loading branch information
Chongxiao Cao authored and Chongxiao Cao committed Jul 22, 2018
1 parent bae2b3c commit 8eb6ad1
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
46 changes: 46 additions & 0 deletions _posts/2018-07-22-post-1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
title: 'Leetcode#5 Longest Palindromic Substring'
date: 2018-07-22
permalink: /posts/leetcode/5
tags:
- Leetcode
---

## Link: ##
https://leetcode.com/problems/longest-palindromic-substring/description/#

## Idea: ##
Dynamic programming:
DP[i][j] = (s[i] == s[j]) && (j-1 > i ? DP[i+1][j-1] : 1);
The second case catches len(s[i][j]) == 2 case.

## Solution: ##
```cpp
class Solution {
public:
string longestPalindrome(string s) {
if(s.size() <= 1)
return s;
int max = 1, max_i = 0, max_j = 0, i, j;
int n = s.size();
bool **DP = (bool**)malloc(n*sizeof(bool*));
for(i = 0; i < n; i++)
DP[i] = (bool*)malloc(n*sizeof(bool));
for(i = 0; i< n; i++)
DP[i][i] = true;

for(i = n - 1; i >= 0; i--) {
for(j = i+1; j < n; j++){
DP[i][j] = (s[i] == s[j]) && (j-1 > i ? DP[i+1][j-1] : 1);
if(DP[i][j] && j-i+1 > max) {
max = j-i+1;
max_i = i;
max_j = j;
}
}
}
return s.substr(max_i, max);
}
};

```
41 changes: 41 additions & 0 deletions _posts/2018-07-22-post-2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
title: 'Leetcode#6 ZigZag Conversion'
date: 2018-07-22
permalink: /posts/leetcode/6
tags:
- Leetcode
---

## Link: ##
https://leetcode.com/problems/zigzag-conversion/description/

## Idea: ##
Convert index reversely.

## Solution: ##
```cpp
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1)
return s;

vector<vector<char>> res(numRows, vector<char>(0, 0));

int factor = numRows + numRows - 2;
for(int i=0; i<s.size(); i++) {
int index = i%factor;
int row_idx = index < numRows ? index : (factor-index);
res[row_idx].push_back(s[i]);
}

string tmp = "";
for (int i = 0; i < numRows; i++){
for(int j=0; j < res[i].size();j++){
tmp = tmp + res[i][j];
}
}
return tmp;
}
};
```

0 comments on commit 8eb6ad1

Please sign in to comment.