您的位置:首页 > 其它

Write a function to find the longest common prefix string amongst an array of strings.

2017-04-14 20:43 639 查看
import java.util.Scanner;
import java.util.logging.Logger;

import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

public class Solution {
public static String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";

for (int j = 0; j < strs[0].length(); ++j){ // 纵向扫描
for (int i = 1; i < strs.length; ++i){
if (j == strs[i].length() ||strs[i].charAt(j) != strs[0].charAt(j))
return strs[0].substring(0, j);
}
}
return strs[0];
}
public static void main(String[] args) {
String strs[] = new String[]{"abcdefg","abcef","abcdeabcg"};
System.out.println(longestCommonPrefix(strs));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐