Leetcode

Valid Word Square

  • Time:O(\Sigma |\texttt{words[i]}|)
  • Space:O(1)

C++

class Solution {
 public:
  bool validWordSquare(vector<string>& words) {
    for (int i = 0; i < words.size(); ++i)
      for (int j = 0; j < words[i].size(); ++j) {
        if (words.size() <= j || words[j].size() <= i)  // out of bound
          return false;
        if (words[i][j] != words[j][i])
          return false;
      }

    return true;
  }
};

JAVA

class Solution {
  public boolean validWordSquare(List<String> words) {
    for (int i = 0; i < words.size(); ++i)
      for (int j = 0; j < words.get(i).length(); ++j) {
        if (words.size() <= j || words.get(j).length() <= i) // out of bound
          return false;
        if (words.get(i).charAt(j) != words.get(j).charAt(i))
          return false;
      }

    return true;
  }
}