LeetCode题解之 Longest Common Prefix

1、题目描述

2、问题分析

直接使用循环解决问题

3、代码

 1 string longestCommonPrefix(vector<string>& strs) {
 2         string res = "";
 3         if(strs.size() == 0)
 4             return res;
 5         
 6         bool isFull = true;
 7         bool isEqual = true;
 8         int pre = 0;
 9         while(isFull &&  isEqual){
10             vector<string>::iterator it = strs.begin();
11             if( pre == (*it).size() ){
12                     isFull = false;
13                     break;
14             }
15             string s1 = (*it).substr(pre,1);
16             
17             for( it = strs.begin() +1 ; it != strs.end(); ++it ){
18                 if( (*it).substr(pre,1) != s1 ){
19                    isEqual = false;
20                     break;
21                 }
22                 
23                 if( pre == (*it).size() ){
24                     isFull = false;
25                     break;
26                 }     
27             }
28             
29             if( isEqual && isFull )
30                 res += s1;
31             pre++;
32         }
33         return res;
34         
35     }
pp
原文地址:https://www.cnblogs.com/wangxiaoyong/p/9944936.html