Write a function to find the longest common prefix string amongst an array of strings.
Example:
Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Solution 1 : (Word by Word Matching)
classSolution{public:stringgetCommonSubstring(string str1,string str2) { string str ="";int i =0, j =0;while (i <str1.length() && j <str2.length()) {if (str1[i] ==str2[j]) { str = str +str1[i]; i++; j++; }else {break; } }return str; }stringlongestCommonPrefix(vector<string> &strs) {if (strs.size() ==0) {return""; }if (strs.size() ==1) {returnstrs[0]; } string s =getCommonSubstring(strs[0],strs[1]);for (int i =2; i <strs.size(); i++) { s =getCommonSubstring(strs[i], s); }return s; }};
I have used a property of associativity. By finding the common prefix between 2 pairs.
Example:-