当前位置:   article > 正文

C++ | Leetcode C++题解之第14题最长公共前缀

C++ | Leetcode C++题解之第14题最长公共前缀

题目:

题解:

  1. class Solution {
  2. public:
  3. string longestCommonPrefix(vector<string>& strs) {
  4. if (!strs.size()) {
  5. return "";
  6. }
  7. int minLength = min_element(strs.begin(), strs.end(), [](const string& s, const string& t) {return s.size() < t.size();})->size();
  8. int low = 0, high = minLength;
  9. while (low < high) {
  10. int mid = (high - low + 1) / 2 + low;
  11. if (isCommonPrefix(strs, mid)) {
  12. low = mid;
  13. }
  14. else {
  15. high = mid - 1;
  16. }
  17. }
  18. return strs[0].substr(0, low);
  19. }
  20. bool isCommonPrefix(const vector<string>& strs, int length) {
  21. string str0 = strs[0].substr(0, length);
  22. int count = strs.size();
  23. for (int i = 1; i < count; ++i) {
  24. string str = strs[i];
  25. for (int j = 0; j < length; ++j) {
  26. if (str0[j] != str[j]) {
  27. return false;
  28. }
  29. }
  30. }
  31. return true;
  32. }
  33. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/427543?site
推荐阅读
相关标签
  

闽ICP备14008679号