fork download
  1. #include <string>
  2. #include <vector>
  3. #include <iostream>
  4.  
  5.  
  6. std::string CommonPrefix(const std::vector<std::string>& words) {
  7. std::string result = "";
  8. int lenght = words.size();
  9. if (lenght == 1) {
  10. result = words[0];
  11. } else {
  12. for (int i = 0; i < lenght; ++i) {
  13. if (i == 0) {
  14. int j = 0;
  15. while ((j < words[i].size()) && (j < words[i + 1].size()) && (words[i][j] == words[i + 1][j])) {
  16. result.push_back(words[i][j]);
  17. ++j;
  18. }
  19. ++i;
  20. } else {
  21. std::string temp = "";
  22. int t = 0;
  23. while ((t < words[i].size()) && (t < result.size()) && (words[i][t] == result[t])) {
  24. temp.push_back(words[i][t]);
  25. ++t;
  26. }
  27. result = temp;
  28. }
  29. }
  30. }
  31. return result;
  32. }
  33.  
  34.  
  35.  
  36. int main() {
  37. std::vector<std::string> v = {"abcdefg", "abcd"};
  38. std::cout << CommonPrefix(v) << std::endl;
  39. }
Success #stdin #stdout 0.01s 5332KB
stdin
Standard input is empty
stdout
abcd