题干:
https://leetcode.cn/problems/valid-sudoku/
检验重复性,自然想到了哈希表…,
我的参考代码如下:
//这次代码由于hashSet对象的作用域问题,导致我调试了很长时间。
//希望以后自己在定义C++的库中类对象时,也不要忘记了初始化,初始化会提醒自己作用域的设定,避免错误。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
//这里应该添加数组值的合法性检验,以及数组大小检验,我省略了
for (int i = 0; i < board.size(); i++) {
unordered_set<char> hashSet{};
for (int j = 0; j < board.size(); j++) { //判断每一行是否符合要求
if (board[i][j] != '.') {
if (hashSet.find(board[i][j]) == hashSet.end()) {
hashSet.insert(board[i][j]);
}
else { return false; }
}
}
hashSet.clear();
}
for (int j = 0; j < board.size(); j++) {
unordered_set<char> hashSet{};
for (int i = 0; i < board.size(); i++) { //判断每一列是否符合要求
if (board[i][j] != '.') {
if (hashSet.find(board[i][j]) == hashSet.end()) {
hashSet.insert(board[i][j]);
}
else { return false; }
}
}
hashSet.clear();
}
//告诫自己,由于hashSet1,2,3的作用域写到了第一个for里面,导致自己调试了很久发现不了错误!
//我是按一行一行读取的
unordered_set<char> hashSet1{};//第一个九宫格
unordered_set<char> hashSet2{};//第二个
unordered_set<char> hashSet3{};//第三个
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board.size(); j++) { //判断每一九宫格是否符合要求
if (j / 3 == 0) {
if (board[i][j] != '.') {
if (hashSet1.find(board[i][j]) == hashSet1.end()) {
hashSet1.insert(board[i][j]);
}
else { return false; }
}
}
else if (j / 3 == 1) {
if (board[i][j] != '.') {
if (hashSet2.find(board[i][j]) == hashSet2.end()) {
hashSet2.insert(board[i][j]);
}
else { return false; }
}
}
else if (j / 3 == 2) {
if (board[i][j] != '.') {
if (hashSet3.find(board[i][j]) == hashSet3.end()) {
hashSet3.insert(board[i][j]);
}
else { return false; }
}
}
}
if (i % 3 == 2) {
hashSet1.clear();
hashSet2.clear();
hashSet3.clear();
}
}
//恭喜你,经过了重重考验
return true;
}
};