如何讀取leetcode中的二維陣列

sky12331發表於2020-10-16

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)=='\"'&&quota.size()!=0) {
				tempVector.push_back(tempString);
				tempString = "";
				quota.pop();
			}
			else if (row.at(i).at(j) == '\"'&&quota.size() == 0) {
				quota.push('\"');
			}
			else if (row.at(i).at(j) != '\"'&&quota.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

相關文章