Valid Word Square
A valid word square means that the kth row and the kth column should read the same string for every k. Let’s define a strategy to check this:
Approach
- Check Number of Rows and Columns: Ensure that the number of rows (i.e., the length of the
words
list) matches the number of columns in the first row (i.e., the length of the first stringwords[0]
). If these are not equal, the word square is not valid. - Iterate Through Rows and Columns: For every row, check if the characters in that row match the characters in the corresponding column.
- Handle Different Lengths: In the given examples, some rows have a smaller length than others. We should take this into consideration and handle it correctly.
Code
Below is the Python code implementing the above approach:
|
|
Explanation
- The outer loop iterates through each row, while the inner loop iterates through each character in the current row.
- We carefully check the corresponding characters in the current row and column. If they do not match, we immediately return
False
. - If the loop completes without finding any mismatches, we return
True
.
Examples
- The function will return
True
for["abcd","bnrt","crmy","dtye"]
and["abcd","bnrt","crm","dt"]
, as they meet the criteria. - It will return
False
for["ball","area","read","lady"]
since the 3rd row and the 3rd column do not match.
The code handles the constraints, including the different lengths of strings in the array, and checks for the validity of the word square as defined in the problem statement.