Longest-Common-Prefix By yusijia November 04 2016 Updated:November 04 2016 Contents 1234/* * Write a function to find the longest common prefix string amongst an array * of strings. */ 求多个字符串的最长公共前缀。 1234567891011121314151617181920212223242526class Solution {public: string longestCommonPrefix(vector<string>& strs) { if(strs.empty()) return ""; int ans = strs[0].size(); for(int i = 1; i < strs.size(); i++){ int s1 = strs[0].size(); int s2 = strs[i].size(); int mins = s1 < s2 ? s1 : s2; ans = ans < mins ? ans : mins; for(int j = 0; j < mins; j++){ if(strs[0][j] != strs[i][j]){ ans = ans < j ? ans : j; break; } } } if(ans == -1){ return ""; }else{ return strs[0].substr(0, ans); } }}; 1234567891011121314151617public class LongestCommonPrefix { public String longestCommonPrefix(String[] strs) { if(strs.length == 0) return ""; int right_most = strs[0].length(); for(int i = 1; i < strs.length; i++) { right_most = Math.min(right_most, strs[i].length()); for(int j = 0; j < right_most; j++) { if(strs[0].charAt(j) != strs[i].charAt(j)) { right_most = j; break; } } } return strs[0].substring(0, right_most); } }