# 【LeetCode】 14. Longest Common Prefix ## Description > 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 "". > 寫一個function在字串陣列中尋找最長共同前字串。 > 如果沒有共同的前字串,回傳空字串""。 ## Example: ``` 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. ``` ## Solution * 把第一個字串的字當作標準,去判斷後面的字串是不是一樣的字。 * 比較需要特別注意的是,陣列為空陣列、或是索引值超出字串範圍。 ### Code ```C++=1 class Solution { public: string longestCommonPrefix(vector<string>& strs) { string str; int count = 0; while(1) { bool isSame = true; if(strs.size()==0 || strs[0].size()<count) break; char c = strs[0][count]; for(int i=1;i<strs.size();i++) { if(strs[i].size()<count||strs[i][count] != c) { isSame = false; break; } } if(isSame) str += c; else break; count++; } return str; } }; ``` ###### tags: `LeetCode` `C++`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up