Write a function to find the longest common prefix string amongst an array of strings.
解题思路:
老实遍历即可,注意边界条件:
JAVA实现:
static public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; for (int i = 0; i < strs[0].length(); i++) { for (int j = 1; j < strs.length; j++) if (strs[j].length() == i || strs[j].charAt(i) != strs[0].charAt(i)) return strs[0].substring(0, i); } return strs[0]; }
C++:
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string>& strs) { 4 if (strs.size() == 0) 5 return ""; 6 for (int i = 0; i < strs[0].length(); i++) { 7 for (int j = 1; j < strs.size(); j++) 8 if (strs[j].length() == i || strs[j][i] != strs[0][i]) 9 return strs[0].substr(0, i); 10 } 11 return strs[0]; 12 } 13 };