Thursday, November 5, 2015

Leetcode: Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question.
Hide Tags
 String


||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
prefix equal the first string then compare to the next one. 
the prefix string will reduce its size each time when no common exist in next string. 
after going through all strings, the left prefix is the wanted one. 

//////////////////////////////////////////////////////////////
//code
       class Solution {
       public:
              string longestCommonPrefix(vector<string>& strs) {
                     string prefix;
                     //check input
                     if (strs.size() == 0)return prefix;
                     prefix = strs[0];
                     for (int i = 1; i<strs.size(); i++){
                           int j = 0, pSize = prefix.size();
                           for (; j<pSize; j++){
                                  if (j >= strs[i].size())break;
                                  if (prefix[j] != strs[i][j])break;
                           }
                           //delete the left chars in prefix
                           if (prefix[j] != prefix.size())prefix.erase(j, prefix.size() - j);
                     }
                     return prefix;
              }
       };




No comments:

Post a Comment