题意:
Write a function to find the longest common prefix string amongst an array of strings. (Easy)
这两天实验室项目太忙了, 老板各种活,只能挑着先水几道easy题,这两个题是昨天做的没来得及写总结。
分析:
暴力的想法遍历比较一下就行,注意遍历的始末位置。优化的话改天再看看discuss
代码:
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string>& strs) { 4 string result; 5 if (strs.size() == 0) { 6 return result; 7 } 8 int minLength = 0x7FFFFFFF; 9 for (int i = 0; i < strs.size(); ++i) { 10 int si = strs[i].size(); 11 minLength = min(minLength, si); 12 } 13 14 for (int i = 0; i < minLength; ++i) { 15 int flag = 0; 16 for (int j = 0; j < strs.size() - 1; ++j) { 17 if (strs[j][i] != strs[j + 1][i]) { 18 flag = 1; 19 break; 20 } 21 } 22 if (flag == 0) { 23 result += strs[0][i]; 24 } 25 if (flag == 1) { 26 break; 27 } 28 } 29 return result; 30 } 31 };
时间: 2024-10-17 09:10:08