c++ solution


  • 0
    W
    class Solution {
    	bool isDigit(char c) {
    		return (c >= '0' && c <= '9') || (c == '-');
    	}
    	NestedInteger getInt(const string& s, int& idx) {
    		int fac = 1;
    		if (s[idx] == '-') {
    			idx += 1;
    			fac = -1;
    		}
    		int i = s[idx] - '0';
    		idx += 1;
    		while (idx < s.size() && isDigit(s[idx])) {
    			i *= 10;
    			i += (s[idx] - '0');
    			idx += 1;
    		}
    		return i * fac;
    	}
    	NestedInteger getList(const string& s, int& idx) {
    		NestedInteger lni;
    		idx += 1;
    		while (idx < s.size()) {
    			if (isDigit(s[idx])) {
    				NestedInteger ni = getInt(s, idx);
    				lni.add(ni);
    				continue;
    			}
    			if (s[idx] == ',') {
    				idx += 1;
    				continue;
    			}
    			if (s[idx] == '[') {
    				NestedInteger slni = getList(s, idx);
    				lni.add(slni);
    				continue;
    			}
    			if (s[idx] == ']') {
    				idx += 1;
    				break;
    			}
    		}
    		return lni;
    	}
    public:
    	NestedInteger deserialize(string s) {
    		NestedInteger res;
    		int idx = 0;
    		if (s[idx] == '[') {
    			NestedInteger lni = getList(s, idx);
    			if (idx >= s.size()) return lni;
    			res.add(lni);
    		}
    		else {
    			NestedInteger ni = getInt(s, idx);
    			if (idx >= s.size()) return ni;
    			res.add(ni);
    		}
    		while (idx < s.size()) {
    			if (s[idx] == '[') {
    				NestedInteger lni = getList(s, idx);
    				res.add(lni);
    				continue;
    			}
    			if (isDigit(s[idx])) {
    				NestedInteger ni = getInt(s, idx);
    				res.add(ni);
    				continue;
    			}
    			idx += 1;
    		}
    		return res;
    	}
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.