Skip to content

Commit e06e815

Browse files
authored
Merge pull request kothariji#601 from Kowsihan-sk/master
added leetcode longest duplicate substring problem
2 parents f140516 + bcbf3d9 commit e06e815

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
4+
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
5+
int n = grid.size(), len = 1;
6+
if(grid[0][0] == 1 || grid[n-1][n-1] == 1) return -1;
7+
if(n==1) return 1;
8+
9+
vector<vector<int>> off = {{0,1},{0,-1},{1,0},{-1,0},{1,1},{-1,-1},{1,-1},{-1,1}};
10+
queue<pair<int,int>> q;
11+
q.push({0,0});
12+
grid[0][0] = 1;
13+
14+
int sz, row, col, i, j;
15+
16+
while(!q.empty()){
17+
sz = q.size();
18+
for(i = 0; i < sz; i++){
19+
row = q.front().first, col = q.front().second;
20+
q.pop();
21+
22+
if(row == n-1 && col == n-1) return len;
23+
24+
for(j = 0; j < 8; j++){
25+
int x = row + off[j][0], y = col + off[j][1];
26+
if(x >= 0 && y >= 0 && x < n && y < n && grid[x][y] == 0){
27+
grid[x][y] = 1;
28+
q.push({x,y});
29+
}
30+
}
31+
32+
}
33+
len++;
34+
}
35+
36+
return -1;
37+
}
38+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
vector<unsigned long long> roll;
2+
3+
class Solution {
4+
public:
5+
bool match(string s, int n, int sz, string &ans){
6+
unordered_map<unsigned long long, vector<int>> mp;
7+
unsigned long long hash = 0;
8+
for(int i = 0; i < sz; i++)
9+
hash = (hash*31 + (s[i] - 'a'));
10+
11+
mp[hash].push_back(0);
12+
13+
for(int i = sz; i < n; i++){
14+
hash = (hash - roll[sz - 1]*(s[i - sz] - 'a'));
15+
hash = (hash*31 + (s[i] - 'a'));
16+
17+
if(mp.count(hash)){
18+
for(int v : mp[hash]){
19+
string t = s.substr(v, sz), c = s.substr(i - sz + 1, sz);
20+
if(t.compare(c) == 0){
21+
ans = t;
22+
return true;
23+
}
24+
}
25+
}
26+
mp[hash].push_back(i - sz + 1);
27+
}
28+
29+
return false;
30+
}
31+
string longestDupSubstring(string s) {
32+
int n = s.length();
33+
if(n == 0) return "";
34+
35+
roll.resize(n);
36+
roll[0] = 1;
37+
for(int i = 1; i < n; i++)
38+
roll[i] = (31*roll[i-1]);
39+
40+
string ans = "", temp;
41+
int l = 1, h = n, mid;
42+
bool flag = false;
43+
44+
while(l <= h){
45+
temp = "";
46+
mid = l + (h-l)/2;
47+
flag = match(s, n, mid, temp);
48+
if(flag){
49+
if(ans.size() < temp.size())
50+
ans = temp;
51+
l = mid+1;
52+
}else h = mid - 1;
53+
}
54+
55+
return ans;
56+
}
57+
};

0 commit comments

Comments
 (0)