Accepted concise C++ solution


  • 12
    I
       bool validWordSquare(vector<string>& words) {
            for(int i = 0; i < words.size(); ++i) {
                for(int j = 0; j < words[i].size(); ++j)             {
                    if(j >= words.size() || words[j].size() <= i || words[j][i] != words[i][j])
                       return false;
                }
            }
            return true;
       }

  • 0
    C

    python version

    class Solution(object):
        def validWordSquare(self, words):
            """
            :type words: List[str]
            :rtype: bool
            """
            for i in range(len(words)):
                for j in range(len(words[i])):
                    if len(words) <= j or len(words[j]) <= i or words[i][j] != words[j][i]:
                        return False
            return True
    

  • 1

    Another Python version:

     def validWordSquare(self, words):
        return all(j < len(words) and i < len(words[j]) and words[j][i] == c
                   for i, word in enumerate(words)
                   for j, c in enumerate(word))

  • 0
    X

    why not j starting from i+1 to eliminate some unnecessary comparisons?

    for(int j = i+1; j < words[i].size(); ++j)   
    

  • 0
    D

    @xinqrs that will fail this kind of test case:
    BALL
    ASEE
    LET
    LEP


Log in to reply
 

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