jayati

Longest Common Prefix

Nov 4th, 2022
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.52 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string longestCommonPrefix(vector<string>& strs) {
  4.         string prefix = strs[0];
  5.         if(strs.size() == 0)
  6.         {
  7.             return "";
  8.         }
  9.         for(int i=1;i<strs.size();i++)
  10.         {
  11.             while(strs[i].find(prefix)!=0)
  12.             {
  13.                 prefix=prefix.substr(0,prefix.length()-1);
  14.             }
  15.             if(prefix.length()==0)
  16.             {
  17.                 return "";
  18.             }
  19.         }
  20.         return prefix;
  21.        
  22.        
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment