Longest Common Prefix
Problem to find the longest common prefix substring.
Example-1:
Input : s = [ "flower", "flow", "flight"] Output : "fl"
Example-2:
Input : s = [ "semicolon", "semifinal"] Output : "semi"
Example-3:
Input : s = [ "discard", "discomfort"] Output : "disc"
Solution
public class Main { public static void main(String[] args) { String[] strs = { "flower", "flow", "flight"}; String prefix = ""; if(strs.length == 0) { prefix = ""; } else { prefix = strs[0]; for(int i = 1; i<strs.length; i++) { while(strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0,prefix.length() -1); if(prefix.isEmpty()) { break; } } } } System.out.println(prefix); } }
s = [ "flower", "flow", "flight"] l = [] k = [] u = [] for x in range(len(s)): k.append(len(s[x])) a = min(k) b = k.index(a) for i in range(len(s)): d = "" for j in range(len(s[b])): if(s[b][j])==(s[i][j]): d += s[b][j] else: break l.append(d) if(len(l) == len(s)): for y in range(len(l)): u.append(len(l[y])) c = min(u) e = u.index(c) print(l[e])
Output
fl