Skip to content

Commit

Permalink
Merge pull request #44 from nhimanshujain/main
Browse files Browse the repository at this point in the history
Longest Repeating Subsequence and  Longest Common Prefix
  • Loading branch information
Manish1Gupta authored Oct 15, 2022
2 parents 5ce39e0 + 3a22526 commit 424dbce
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Longest Common Prefix.java
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);
}
31 changes: 31 additions & 0 deletions Longest Repeating Subsequence.py
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)

0 comments on commit 424dbce

Please sign in to comment.