如何读取leetcode中的二维数组
程序员文章站
2022-05-12 10:42:01
...
leetcoe中二维数组的输入为如下形式,在本地测试的时候读取很不方便,简单写了个函数封装了读取的方法
[
[“5”,“3”,".",".",“7”,".",".",".","."],
[“6”,".",".",“1”,“9”,“5”,".",".","."],
[".",“9”,“8”,".",".",".",".",“6”,"."],
[“8”,".",".",".",“6”,".",".",".",“3”],
[“4”,".",".",“8”,".",“3”,".",".",“1”],
[“7”,".",".",".",“2”,".",".",".",“6”],
[".",“6”,".",".",".",".",“2”,“8”,"."],
[".",".",".",“4”,“1”,“9”,".",".",“5”],
[".",".",".",".",“8”,".",".",“7”,“9”]
]
使用C++读取该输入,并返回一个二维数组
#include <iostream>
#include<vector>
#include<stack>
#include<string>
using namespace std;
vector<vector<string>> leetcode2DInput() {
vector<string> row;
vector<vector<string>> output;
stack<char> parentheses;
stack<char> quota;
parentheses.push('0');
string S;
cin >> S;
while (1) {
string tempString="";
for (int i = 0; i < S.length(); i++) {
if (S.at(i) == '[') {
parentheses.push(S.at(i));
}
else if (S.at(i) == ']') {
row.push_back(tempString);
parentheses.pop();
tempString = "";
}
else {
if (parentheses.size() == 3) {
string temp(1, S.at(i));
tempString.append(temp);
}
}
}
if (parentheses.size() != 1) {
cin >> S;
}
else {
break;
}
}
row.pop_back();
string tempString="";
vector<string> tempVector;
for (int i = 0; i < row.size(); i++) {
quota.push(row.at(i).at(0));
for (int j = 1; j < row.at(i).length(); j++) {
if (row.at(i).at(j)=='\"'&"a.size()!=0) {
tempVector.push_back(tempString);
tempString = "";
quota.pop();
}
else if (row.at(i).at(j) == '\"'&"a.size() == 0) {
quota.push('\"');
}
else if (row.at(i).at(j) != '\"'&"a.size() != 0) {
string temp(1,row.at(i).at(j));
tempString.append(temp);
}
else {
continue;
}
}
output.push_back(tempVector);
tempVector.clear();
}
for (int i = 0; i < output.size(); i++) {
for (int j = 0; j < output.at(i).size(); j++) {
cout << output.at(i).at(j)<<" ";
}
cout << endl;
}
return output;
}
int main()
{
leetcode2DInput();
}
读取结果
5 3 . . 7 . . . .
6 . . 1 9 5 . . .
. 9 8 . . . . 6 .
8 . . . 6 . . . 3
4 . . 8 . 3 . . 1
7 . . . 2 . . . 6
. 6 . . . . 2 8 .
. . . 4 1 9 . . 5
. . . . 8 . . 7 9
下一篇: 求数组的最大值和次大值、最大值和最小值