Skip to content

Commit

Permalink
Added string problems
Browse files Browse the repository at this point in the history
  • Loading branch information
sunny0910 committed Feb 23, 2020
1 parent f002444 commit f3d503d
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 0 deletions.
File renamed without changes.
33 changes: 33 additions & 0 deletions strings/longest_common_substring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
def lcs(i, j):
if i == 0 or j == 0:
return 0
count = 0
if a[i-1] == b[j-1]:
return 1 + lcs(i-1, j-1)
else:
return max(count, lcs(i-1, j), lcs(i, j-1))


def lcs_op(x, y, i, j):
answers = [[0 for columns in range(i+1)] for rows in range(j+1)]

result = 0

for m in range(i+1):
for n in range(j+1):
if m == 0 or n == 0:
answers[m][n] = 0
elif x[m-1] == y[n-1]:
answers[m][n] = 1 + answers[m-1][n-1]
result = max(result, answers[m][n])
else:
answers[m][n] = 0
return result

a = "abcdxyz"
b = "xyzabcd"
m = len(a)
n = len(b)
x = lcs(m, n)
x = lcs_op(a, b, m, n)
print(x)
34 changes: 34 additions & 0 deletions strings/lps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
def lps(a, i, j):
if not a:
return -1
if i == j:
return 1
if a[i] == a[j] and j == i+1:
return 2
if a[i] == a[j]:
return 2 + lps(a, i+1, j-1)
else:
return max(lps(a, i, j-1), lps(a, i+1, j))


def lps_op(a):
n = len(a)
answers = [[0 for i in range(n)] for i in range(n)]
for i in range(n):
answers[i][i] = 1
for cl in range(2, n+1):
for i in range(n-cl+1):
j = i+cl-1
if a[i] == a[j] and cl == 2:
answers[i][j] = 2
elif a[i] == a[j]:
answers[i][j] = 2 + answers[i+1][j-1]
else:
answers[i][j] = max(answers[i][j-1], answers[i+1][j])
return answers[0][n-1]


s = "GEEKSFORGEEKS"
x = lps(s, 0, len(s)-1)
x = lps_op(s)
print(x)
20 changes: 20 additions & 0 deletions strings/word_break_problem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
def word_found(a):
if not a:
return
i = 0
j = 1
found_words = []
while j <= len(a):
word = a[i:j]
if word in all_word:
found_words.append(word)
i = j
if j == len(a):
return found_words
continue
j += 1
return False

all_word = ["i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"]
x = "ilikesam"
print(word_found(x))

0 comments on commit f3d503d

Please sign in to comment.