Skip to content

Instantly share code, notes, and snippets.

@rdtr
Last active January 6, 2016 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdtr/6ca3699e82683e2a63ec to your computer and use it in GitHub Desktop.
Save rdtr/6ca3699e82683e2a63ec to your computer and use it in GitHub Desktop.
algorithm_string_longest_common_prefix
public class Solution {
public String longestCommonPrefix(String[] strs) {
int leng = strs.length;
if (leng == 0) return "";
else if (leng == 1) return strs[0];
// check the minimum length among all strings
int minLen = strs[0].length();
String minStr = strs[0];
for (int i = 1; i < leng; i++) {
if (strs[i].length() < minLen) {
minLen = strs[i].length();
minStr = strs[i];
}
}
for (int j = 0; j < minLen; j++) {
char ch = strs[0].charAt(j);
for (int k = 1; k < leng; k++) {
char _ch = strs[k].charAt(j);
if (ch != _ch) {
return minStr.substring(0, j);
}
}
}
return minStr;
}
}
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
strsNum = len(strs)
if strsNum == 0: return ''
elif strsNum == 1: return strs[0]
# check the minimum length among all strings
minLen, minStr = len(strs[0]), strs[0]
for st in strs:
if len(st) < minLen:
minLen, minStr = len(st), st
# check all string from one index to another
for i in range(minLen):
c = strs[0][i]
for j in range(strsNum):
_c = strs[j][i]
if c != _c:
return minStr[0:i]
return minStr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment