中级农民
- 积分
- 110
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-7-28
- 最后登录
- 1970-1-1
|
好吧,我就再写一遍代码。以下是测试通过的。不过我按照面试中的输入格式,把JSON中的空格和换行都除去了。
- #include <iostream>
- #include <string>
- #include <unordered_set>
- #include <cctype>
- using namespace std;
- class Solution {
- unordered_set<string> primaryKeys, secondaryKeys;
- string primaryValue = "", secondaryValue = "";
- int findMatchingBracket(string s, int pos, string brackets) {
- int cnt = 0, n = s.length();
- for (int j = pos; j < n; j++) {
- if (s[j] == brackets[0]) cnt++;
- if (s[j] == brackets[1]) cnt--;
- if (cnt == 0) return j;
- }
- }
- int findMatchingQuotation(string s, int pos) {
- int n = s.length();
- for (int j = pos + 1; j < n; j++)
- if (s[j] == '"' && s[j - 1] != '\\') return j;
- }
- void findKey(string obj) {
- int n = obj.length();
- for (int i = 0; i < n; i++) {
- if (obj[i] != '"') continue;
- int endOfKey = findMatchingQuotation(obj, i);
- int startOfValue = endOfKey + 2, endOfValue;
- string key = obj.substr(i + 1, endOfKey - i - 1), value;
- // value is an object
- if (obj[startOfValue] == '{')
- endOfValue = findMatchingBracket(obj, startOfValue, "{}");
- // value is an array
- if (obj[startOfValue] == '[')
- endOfValue = findMatchingBracket(obj, startOfValue, "[]");
- // value is a number
- if (isdigit(obj[startOfValue]))
- endOfValue = obj.find_first_not_of("0123456789.", startOfValue + 1) - 1;
- // value is a string
- if (obj[startOfValue] == '"')
- endOfValue = findMatchingQuotation(obj, startOfValue);
- value = obj.substr(startOfValue, endOfValue - startOfValue + 1);
- if (primaryKeys.count(key)) {
- primaryValue = value;
- return;
- }
- if (secondaryValue == "" && secondaryKeys.count(key))
- secondaryValue = value;
- if (value[0] == '{') findKey(value);
- if (primaryValue != "") return;
- i = endOfValue;
- }
- }
- public:
- string getValue(string obj, unordered_set<string> primary, unordered_set<string> secondary) {
- primaryKeys = primary;
- secondaryKeys = secondary;
- findKey(obj);
- return primaryValue != "" ? primaryValue : secondaryValue;
- }
- };
- int main() {
- Solution sol;
- string s = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"sex\":\"male\",\"age\":25,\"address\":{\"streetAddress\":\"212ndStreet\",\"city\":\"NewYork\",\"state\":\"NY\",\"postalCode\":\"10021\"},\"phoneNumber\":[{\"type\":\"home\",\"number\":\"212555-1234\"},{\"type\":\"fax\",\"number\":\"646555-4567\"}]}";
- cout << sol.getValue(s, {"streetAddress"}, {"age"}) << endl;
- return 0;
- }
复制代码 |
|