题目描述:Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
代码如下:
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if(strs.empty()) return ""; //用strs[0][0]与strs[1][0]、strs[2][0]……比较 //用strs[0][1]与strs[1][1]、strs[2][1]……比较 for(int index = 0; index < strs[0].size(); index++){ for(int i = 1; i <strs.size(); i++){ if(strs[i][index] != strs[0][index]) return strs[0].substr(0, index); } } return strs[0]; } };
Java:
public String longestCommonPrefix(String[] strs) { if (strs.length == 0) { return ""; } for (int index = 0; index < strs[0].length(); index++) { for (int i = 0; i < strs.length; i++) { //要考虑后面字符串长度小的情况 if (index < strs[i].length()) { if (strs[i].charAt(index) != strs[0].charAt(index)) { return strs[0].substring(0, index); } }else { return strs[i]; } } } return strs[0]; }