1.Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
(求一个字符串数组中最长的公共前缀)
Example:
{“ss”,”ssh”,”sshc”,”sc”}
return “s”;
思路:循环每个字符串,使用charAt()方法找出代码单元,如果相同通过StringBuilder连接返回。
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs==null || strs.length==0){
return "";
}
String temp = strs[0];
for (int i=0;i<strs.length;i++){
StringBuilder sb = new StringBuilder();
int length = 0;
if (temp.length() >= strs[i].length()){
length = strs[i].length();
}else {
length = temp.length();
}
for(int j=0;j<length;j++){
if(temp.charAt(j) == strs[i].charAt(j)){
sb.append(temp.charAt(j));
}else{
break;
}
}
temp = sb.toString();
}
return temp;
}
public static void main(String[] args) {
LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix();
String[] s = {"ssh","ss","ssb","sshc"};
System.out.println(longestCommonPrefix.longestCommonPrefix(s));
}
}