g*l 发帖数: 385 | 1 出现过几次了, 没看见简洁好的解发. 有大侠给个 code? 谢谢.
写出json_pretty的code实现。介绍一下背景,json是一种数据交换格式,基于
JaveScript的。json object就是string key和value的集合。json_pretty就是把一个
一行的json string转换为容易被人阅读的格式。比如:
输入:{“id”:"id-123","woe_id":[123,456,789],"attribute":{"title":"a","desc
":"b"}}
输出:{
“id”:"id-123",
"woe_id":[123,456,789],
"attribute":{
"title":"a",
"desc":"b"
}
}
要逐层缩进。 | g*l 发帖数: 385 | 2 不是大侠, 也可以帖 code 试试, 别光看帖 呵呵.
desc
【在 g*l 的大作中提到】 : 出现过几次了, 没看见简洁好的解发. 有大侠给个 code? 谢谢. : 写出json_pretty的code实现。介绍一下背景,json是一种数据交换格式,基于 : JaveScript的。json object就是string key和value的集合。json_pretty就是把一个 : 一行的json string转换为容易被人阅读的格式。比如: : 输入:{“id”:"id-123","woe_id":[123,456,789],"attribute":{"title":"a","desc : ":"b"}} : 输出:{ : “id”:"id-123", : "woe_id":[123,456,789], : "attribute":{
| i**********e 发帖数: 1145 | 3 不是大侠,贴一贴我的代码,代码如果不好看 请多多包涵
恐怕只能 handle 以上的 sample test case。
基本思路就是递归,如果有更复杂的情况可以再慢慢改进。
#include
#include
#include
using namespace std;
const int TAB_SPACE = 4;
void outputJSon(istream &in, int indentLevel) {
bool firstChar = true;
bool inBracket = false;
while (in) {
char c = in.get();
if (firstChar) {
cout << endl << setw(indentLevel) << c;
firstChar = false;
}
else {
cout << c;
}
if (c == '{') {
outputJSon(in, indentLevel+TAB_SPACE);
c = in.get();
assert(c == '}');
cout << endl << setw(indentLevel) << "}";
firstChar = true;
} else if (!inBracket && c == ',') {
firstChar = true;
} else if (c == '[') {
inBracket = true;
} else if (c == ']') {
inBracket = false;
}
if (in.peek() == '}') {
return;
}
}
}
int main() {
//freopen("data.txt", "r", stdin);
outputJSon(cin, 0);
}
一些常见面试题的答案与总结 -
http://www.ihas1337code.com | i**********e 发帖数: 1145 | 4 其实不递归 代码或许会更简单些
void outputJSon(istream &in) {
bool newLine = false;
bool inBracket = false;
int indentLevel = 0;
while (in) {
char c = in.get();
if (newLine) {
cout << endl << setw(indentLevel) << c;
newLine = false;
}
else {
cout << c;
}
if (c == '{') {
indentLevel += TAB_SPACE;
newLine = true;
} else if (!inBracket && c == ',') {
newLine = true;
} else if (c == '}') {
newLine = true;
} else if (c == '[') {
inBracket = true;
} else if (c == ']') {
inBracket = false;
}
if (in.peek() == '}') {
indentLevel -= TAB_SPACE;
newLine = true;
}
}
}
一些常见面试题的答案与总结 -
http://www.ihas1337code.com | c******n 发帖数: 4965 | 5 多谢,
我原来写的deserialize binary tree, 非找matching ) 才去做recursive parsing
你这样直接consume ")" ( 加assert) 简单多了
【在 i**********e 的大作中提到】 : 不是大侠,贴一贴我的代码,代码如果不好看 请多多包涵 : 恐怕只能 handle 以上的 sample test case。 : 基本思路就是递归,如果有更复杂的情况可以再慢慢改进。 : #include : #include : #include : using namespace std; : const int TAB_SPACE = 4; : void outputJSon(istream &in, int indentLevel) { : bool firstChar = true;
|
|