Advertisement
chevengur

Longest Common Prefix

Apr 25th, 2023
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. class Solution {
  6. public:
  7.  
  8.     std::string prefix;
  9.  
  10.     std::string longestCommonPrefix(std::vector<std::string>& strs) {
  11.         std::string prefix = strs[0];                                   //flower
  12.  
  13.         for (int i = 0; i < strs.size(); ++i) {                         //пробегаем циклом по всему вектору
  14.                                                                        
  15.             while (strs[i].find(prefix) != 0) {                         //flower.поиск_первого_вхождения(flower) != 0
  16.                 prefix = prefix.substr(0, prefix.length() - 1);         //уменьшаем на единичку префикс
  17.                 if (prefix.empty()) {
  18.                     return "";
  19.                 }
  20.             }
  21.         }
  22.  
  23.         return prefix;
  24.     }
  25.  
  26.     void getdata() {
  27.         std::cout << prefix;
  28.     }
  29. };
  30.  
  31. int main() {
  32.     using namespace std;
  33.     Solution sol;
  34.     vector<string> strs = { "flower", "flow", "flight" };
  35.     sol.longestCommonPrefix(strs);
  36.     sol.getdata();
  37.  
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement