C++ Leetcode初級演算法之最長公共字首
阿新 • • 發佈:2018-11-28
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串 “”。
示例 1:
輸入: [“flower”,“flow”,“flight”]
輸出: “fl”
示例 2:
輸入: [“dog”,“racecar”,“car”]
輸出: “”
解釋: 輸入不存在公共字首。
說明:
所有輸入只包含小寫字母 a-z 。
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.empty()) return ""; string first = strs[0]; for(int i=1;i<strs.size();i++) for(int j=0;j<first.size();j++) if(strs[i][j] != first[j]) { first.resize(j); break; } return first; } };