HachiLei's Blog
订阅

Sscanf的使用

sscanf为C标准库函数,其写法为:

int sscanf(const char *str, const char *format, ...)

该函数用于从字符串读取格式化输入,其中*str可以用C++中string类型进行替换,实现更方便的操作。

这是在力扣 Q3.函数独占时间 一题中出现的写法,相较于使用逐个substr来取":"分隔的数据更高效、简洁。
力扣原题:https://leetcode.cn/problems/exclusive-time-of-functions?envType=problem-list-v2&envId=shujujiegouyusuanfa-xianxingqiantan-zhan

代码题解:

class Solution {
public:
    vector<int> exclusiveTime(int n, vector<string>& logs) {
        stack<pair<int, int>> st; // {idx, 开始运行的时间}
        vector<int> res(n, 0);
        for (auto& log : logs) {
            char type[10];
            int idx, timestamp;
            sscanf(log.c_str(), "%d:%[^:]:%d", &idx, type, &timestamp);
            if (type[0] == 's') {
                if (!st.empty()) {
                    res[st.top().first] += timestamp - st.top().second;
                    st.top().second = timestamp;
                }
                st.emplace(idx, timestamp);
            } else {
                auto t = st.top();
                st.pop();
                res[t.first] += timestamp - t.second + 1;
                if (!st.empty()) {
                    st.top().second = timestamp + 1;
                }
            }
        }
        return res;
    }
};