首页 > 其他 > 详细

Leetcode 14. Longest Common Prefix(水)

时间:2019-08-31 11:36:39      阅读:54      评论:0      收藏:0      [点我收藏+]
14. Longest Common Prefix
Easy

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 top = 0;
 5         int fl = 1;
 6         int len = strs.size();
 7         if(len==0) return "";
 8         if(len==1) return strs[0];
 9         while(fl){
10             for (int i = 1 ;i < len; i++){
11                 if(top>strs[i].length()||top>strs[i-1].length()||strs[i][top]!=strs[i-1][top]){
12                     fl = 0;
13                     break;
14                 }
15             }
16             top++;
17         }
18         top--;
19         if(top==0) return "";
20         return strs[0].substr(0,top);
21     }
22 };

 

Leetcode 14. Longest Common Prefix(水)

原文:https://www.cnblogs.com/shanyr/p/11438283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!