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
.
题目大意:
输入字符串数组,输出这些字符串的最大公共子串。
理 解 :
用当前公共子串与其他字符串比较,保留两字符串的最大公共串作为当前公共串。
代 码 C++:
class Solution { public: string longestCommonPrefix(vector<string>& strs) { string commonStr; int n,i,j,len,lastLen; n = strs.size(); if(n==0) return ""; commonStr = strs[0]; len = commonStr.length(); lastLen = len; for(i=1;i<n;++i){ if(commonStr==" ") return ""; j = 0; while(commonStr[j]==strs[i][j] && commonStr[j]!=‘\0‘ && strs[i][j]!=‘\0‘){ ++j; } lastLen = j; while(j<len){ commonStr[++j] = ‘ ‘; } commonStr[lastLen] = ‘\0‘; len = lastLen; } return commonStr; } };
leetcode [14] - Longest Common Prefix
原文:https://www.cnblogs.com/lpomeloz/p/10944234.html