Given a sequence of words, check whether it forms a valid word square.
A sequence of words forms a valid Word square if the kth row and column read the exact same string, where 0≤ K < Max (NumRows, NumColumns).
Note:
- The number of words given is at least 1 and does not exceed 500.
- Word length would be is at least 1 and does not exceed 500.
- Each of the word contains only lowercase 中文版 alphabet
a-z .
Example 1:
input:[ "ABCD", "BNRT", "Crmy", "Dtye"]output:trueexplanation:the first row and first column both Read "ABCD". The second row and second column both read "BNRT". The third row and third column both read "Crmy". The fourth row and fourth column both read "Dtye". Therefore, it is a valid word square.
Example 2:
input:[ "ABCD", "BNRT", "CRM", "DT"]output:trueexplanation:the first row and first column both read " ABCD. " The second row and second column both read "BNRT". The third row and third column both read "CRM". The fourth row and fourth column both read "DT". Therefore, it is a valid word square.
Example 3:
input:[ ' Ball ', ' area ', ' read ', ' lady ']output:falseexplanation:the third row reads ' Read ' while The third column reads "Lead". Therefore, it's not a valid word square.
This problem gives us a two-bit array, each row of each column is a word, need to satisfy the K line of words and K-column of the word to be equal, here does not require the length of each word is the same, as long as the corresponding position of the word. So here is actually a traversal of the two-dimensional array, and then verify that the corresponding bit of the character is equal, because the lines of the word length is not necessarily equal, so we find the corresponding position of the character, we must first determine whether the cross-border, that is, the corresponding position is a character exists, where the non-conformance to the place directly return false Return true at the end of all traversal, see the code below:
classSolution { Public: BOOLValidwordsquare (vector<string>&words) { if(Words.empty ())return true; if(Words.size ()! = words[0].size ())return false; for(inti =0; I < words.size (); ++i) { for(intj =0; J < Words[i].size (); ++j) {if(J >= words.size () | | I >= words[j].size () | | words[i][j]! =Words[j][i]) { return false; } } } return true; }};
Resources:
Https://discuss.leetcode.com/topic/63387/java-ac-solution-easy-to-understand
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Valid Word Square to verify the word squared