-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #44 from nhimanshujain/main
Longest Repeating Subsequence and Longest Common Prefix
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
public String longestCommonPrefix(String[] strs) { | ||
if (strs == null || strs.length == 0) return ""; | ||
return longestCommonPrefix(strs, 0 , strs.length - 1); | ||
} | ||
|
||
private String longestCommonPrefix(String[] strs, int l, int r) { | ||
if (l == r) { | ||
return strs[l]; | ||
} | ||
else { | ||
int mid = (l + r)/2; | ||
String lcpLeft = longestCommonPrefix(strs, l , mid); | ||
String lcpRight = longestCommonPrefix(strs, mid + 1,r); | ||
return commonPrefix(lcpLeft, lcpRight); | ||
} | ||
} | ||
|
||
String commonPrefix(String left,String right) { | ||
int min = Math.min(left.length(), right.length()); | ||
for (int i = 0; i < min; i++) { | ||
if ( left.charAt(i) != right.charAt(i) ) | ||
return left.substring(0, i); | ||
} | ||
return left.substring(0, min); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
class Solution: | ||
|
||
def longestCommonSubsequence(self, text1, text2): | ||
|
||
dp = [[0] * (len(text1)+1) for i in range(len(text2)+1)] | ||
|
||
for i in range(1,len(text2)+1): | ||
for j in range(1,len(text1)+1): | ||
|
||
if text2[i-1] == text1[j-1] and i != j: | ||
dp[i][j] = dp[i-1][j-1] + 1 | ||
|
||
else: | ||
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) | ||
|
||
# print(dp) | ||
return dp[len(text2)][len(text1)] | ||
|
||
|
||
def LongestRepeatingSubsequence(self, str): | ||
# Code here | ||
return self.longestCommonSubsequence(str, str) | ||
|
||
|
||
if __name__ == '__main__': | ||
T=int(input()) | ||
for i in range(T): | ||
str = input() | ||
ob = Solution() | ||
ans = ob.LongestRepeatingSubsequence(str) | ||
print(ans) |