C++ readable solution


  • 0
    O
         string longestCommonPrefix(vector<string>& strs) 
        {
            string prefix = "";
            
            if(strs.size() == 0 || strs[0].length() == 0 )
                return "";
            
            int characterIndex = 0;
            char currentSharedCharacter = strs[0][characterIndex];
            char currentCharacter;
            
            while(currentSharedCharacter != '\0')
            {
                bool isCharacterDifferent = false;
                for(int i = 0; i < strs.size() ; i++)
                {
                    currentCharacter = strs[i][characterIndex];
                    
                    if(currentCharacter != currentSharedCharacter || currentCharacter == '\0')
                    {
                        isCharacterDifferent = true;
                        break;
                    }
                }
                
                if(isCharacterDifferent)
                    break;
                
                prefix.push_back(currentSharedCharacter);
                currentSharedCharacter = strs[0][++characterIndex];
            }
            
            return prefix;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.