首页 > 代码库 > Longest Common Prefix

Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

思路:依次比较即可。

 1 class Solution { 2 public: 3     string longestCommonPrefix( vector<string> &strs ) { 4         if( strs.empty() ) { return string(""); } 5         int start = -1; 6         while( ++start < strs[0].length() ) { 7             for( int i = (int)strs.size()-1; i > 0; --i ) { 8                 if( strs[i][start] != strs[0][start] ) { return strs[0].substr( 0, start ); } 9             }10         }11         return strs[0].substr( 0, start );12     }13 };

 

Longest Common Prefix