#ifndef STRINGHANDLER_H #define STRINGHANDLER_H #include <string> #include <vector> #include <stack> #include <algorithm> using namespace std; class StringHandler { public: StringHandler(); string removeDuplicateLetters(string s); private: vector<int> count; vector<bool> inStack; stack<char> st; }; StringHandler::StringHandler() : count(26, 0), inStack(26, false) {} string StringHandler::removeDuplicateLetters(string s) { for (char c : s) { count[c - 'a']++; } for (char c : s) { count[c - 'a']--; if (inStack[c - 'a']) { continue; } while (!st.empty() && st.top() > c && count[st.top() - 'a'] > 0) { inStack[st.top() - 'a'] = false; st.pop(); } st.push(c); inStack[c - 'a'] = true; } string ans = ""; while (!st.empty()) { ans += st.top(); st.pop(); } reverse(ans.begin(), ans.end()); return ans; } #endif // STRINGHANDLER_H解释每一行代码
时间: 2023-12-06 11:43:23 浏览: 22
1. `#ifndef STRINGHANDLER_H` - 如果未定义宏`STRINGHANDLER_H`,则进入条件编译。
2. `#define STRINGHANDLER_H` - 定义宏`STRINGHANDLER_H`,保证头文件只被编译一次。
3. `#include <string>` - 包含头文件`string`,提供字符串操作的功能。
4. `#include <vector>` - 包含头文件`vector`,提供向量操作的功能。
5. `#include <stack>` - 包含头文件`stack`,提供栈操作的功能。
6. `#include <algorithm>` - 包含头文件`algorithm`,提供算法操作的功能。
7. `using namespace std;` - 引入命名空间`std`。
8. `class StringHandler {` - 定义类`StringHandler`。
9. `public:` - 公共访问权限。
10. `StringHandler();` - 默认构造函数。
11. `string removeDuplicateLetters(string s);` - 定义函数`removeDuplicateLetters`,输入字符串`s`,输出去除重复字母后的字符串。
12. `private:` - 私有访问权限。
13. `vector<int> count;` - 定义向量`count`,存储每个字母出现的次数。
14. `vector<bool> inStack;` - 定义向量`inStack`,表示每个字母是否在栈中。
15. `stack<char> st;` - 定义栈`st`,存储字符。
16. `StringHandler::StringHandler() : count(26, 0), inStack(26, false) {}` - 类`StringHandler`的默认构造函数,初始化`count`和`inStack`向量。
17. `string StringHandler::removeDuplicateLetters(string s) {` - 函数`removeDuplicateLetters`的定义,输入字符串`s`,返回去重后的字符串。
18. `for (char c : s) { count[c - 'a']++; }` - 遍历字符串`s`中的每个字符,统计每个字符出现的次数。
19. `for (char c : s) {` - 再次遍历字符串`s`中的每个字符。
20. `count[c - 'a']--;` - 减少字符`c`的出现次数。
21. `if (inStack[c - 'a']) { continue; }` - 如果字符`c`在栈中,则跳过本次循环。
22. `while (!st.empty() && st.top() > c && count[st.top() - 'a'] > 0) {` - 当栈顶元素大于字符`c`且栈顶元素后面还有相同字符时,弹出栈顶元素。
23. `inStack[st.top() - 'a'] = false;` - 将栈顶元素标记为不在栈中。
24. `st.pop();` - 弹出栈顶元素。
25. `st.push(c);` - 将字符`c`压入栈中。
26. `inStack[c - 'a'] = true;` - 将字符`c`标记为在栈中。
27. `} string ans = "";` - 声明字符串`ans`,用于存储去重后的字符串。
28. `while (!st.empty()) { ans += st.top(); st.pop(); }` - 将栈中元素依次弹出,加入到字符串`ans`中。
29. `reverse(ans.begin(), ans.end());` - 将字符串`ans`反转。
30. `return ans;` - 返回去重后的字符串。
31. `#endif // STRINGHANDLER_H` - 结束条件编译。