Valid Word Square
Problem
Given an array of strings words
, return true
if it forms a valid word square.
A sequence of strings forms a valid word square if the kth
row and column read the same string, where 0 <= k < max(numRows, numColumns)
.
Constraints
1 <= words.length <= 500
1 <= words[i].length <= 500
words[i]
consists of only lowercase English letters.
Solution
The problem Valid Word Square
can be solved by iterating through all characters in all given strings while checking if a diagonal character can exists, and if so, then if they are identical.
Implementation
class Solution
{
public:
bool validWordSquare(vector<string> &words)
{
for (int i = 0; i < words.size(); i++)
for (int j = 0; j < words[i].length(); j++)
if (words.size() <= j || words[j].length() <= i || words[i][j] != words[j][i])
return false;
return true;
}
};