leetcode 14. Longest Common Prefix

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 len = strs.size();
 5         if (len == 0)
 6             return "";
 7         for (int i = 0; i < strs[0].length(); ++i) {
 8             char c = strs[0][i];
 9             for (int j = 1; j < strs.size(); ++j) {
10                 if (i < strs[j].length() && strs[j][i] == c) {
11                     continue;
12                 } else {
13                     return strs[0].substr(0, i);
14                 }
15             }
16         }
17         return strs[0];
18     }
19 };

 

posted @ 2019-09-20 09:37  琴影  阅读(193)  评论(0编辑  收藏  举报