Scribbling

[C++] ostringstream, isdigit 본문

Computer Science/C++

[C++] ostringstream, isdigit

focalpoint 2023. 8. 29. 00:48

 

LeetCode: 394. Decode String

https://leetcode.com/problems/decode-string/description/

 

Decode String - LeetCode

Can you solve this real interview question? Decode String - Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is g

leetcode.com

class Solution {
public:

    int idx = 0;
    string s;

    string decodeString(string s) {
        this->s = s;
        return helper();
    }

    string helper() {
        ostringstream oss;
        while (idx < s.size()) {
            if (isdigit(s[idx])) {
                int num = 0;
                while (s[idx] != '[') {
                    num = num * 10 + s[idx] - '0';
                    idx++;
                }
                idx++;
                string str = helper();
                for (int t = 0; t < num; t++) {
                    oss << str;
                }
            }
            else if (s[idx] == ']') {
                idx++;
                return oss.str();
            }
            else {
                oss << s[idx];
                idx++;
            }
        }
        return oss.str();
    }
};

'Computer Science > C++' 카테고리의 다른 글

[C++] unordered_map, unordered_set, substr  (0) 2023.08.31
[C++] vector sum, vector max  (0) 2023.08.31
[C++] to_string, deque, string split  (0) 2023.08.24
[C++] istringstream  (0) 2023.08.22
[C++] Chapter 2: Types  (0) 2023.08.21