leetcode: Longest Common Prefix
http://oj.leetcode.com/problems/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 (0 == strs.size()) { 5 return string(); 6 } 7 8 int i = 0; 9 bool stop = false; 10 11 while (!stop) { 12 char ch = '\0'; 13 vector<string>::const_iterator it; 14 15 for (it = strs.begin(); it != strs.end(); ++it) { 16 if (i < it->length()) { 17 if ('\0' == ch) { 18 ch = (*it)[i]; 19 } 20 else { 21 if (ch != (*it)[i]) { 22 stop = true; 23 break; 24 } 25 } 26 } 27 else { 28 stop = true; 29 break; 30 } 31 } 32 33 ++i; 34 } 35 36 return strs[0].substr(0, i - 1); 37 } 38 };