Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string>& strs) { 4 int top = 0; 5 int fl = 1; 6 int len = strs.size(); 7 if(len==0) return ""; 8 if(len==1) return strs[0]; 9 while(fl){ 10 for (int i = 1 ;i < len; i++){ 11 if(top>strs[i].length()||top>strs[i-1].length()||strs[i][top]!=strs[i-1][top]){ 12 fl = 0; 13 break; 14 } 15 } 16 top++; 17 } 18 top--; 19 if(top==0) return ""; 20 return strs[0].substr(0,top); 21 } 22 };
Leetcode 14. Longest Common Prefix(水)
原文:https://www.cnblogs.com/shanyr/p/11438283.html