本文主要是介绍14. Longest Common Prefix(Leetcode每日一题-2020.06.15),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
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 “”.
All given inputs are in lowercase letters a-z.
Example1
Input: [“flower”,“flow”,“flight”]
Output: “fl”
Example2
Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.
Solution
class Solution {
public:string longestCommonPrefix(vector<string> &strs) {if(strs.empty())return "";string ret = strs[0];for(auto &str:strs){int len =min(ret.length(),str.length());int i = 0;while(i<len){if(ret[i] != str[i])break;++i;}if(i < ret.length())ret = ret.substr(0,i);}return ret;}
这篇关于14. Longest Common Prefix(Leetcode每日一题-2020.06.15)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!