请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek()返回队列开头的元素
boolean empty() 如果队列为空,返回true ;否则,返回false
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int res = stOut.top();
stOut.pop();
return res;
}
int peek() {
int res = this->pop();
stOut.push(res);
return res;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop()移除并返回栈顶元素。
int top()返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {//用两个队列实现
int top;
while(que1.size()>1){
que2.push(que1.front());
que1.pop();
}
top=que1.front();
que1.pop();
que1 = que2;
while(!que2.empty()){
que2.pop();
}
return top;
}
// int pop() {//用一个队列实现
// int top,size=que1.size()-1;
// while(size--){
// que1.push(que1.front());
// que1.pop();
// }
// top=que1.front();
// que1.pop();
// return top;
// }
int top() {
return que1.back();
}
bool empty() {
return que1.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
3、每个右括号都有一个对应的相同类型的左括号。
法一:
class Solution {
public:
bool isValid(string s) {
bool flag=true;
stack<char> stack;
for(char c:s){
if(c=='(' || c=='[' || c=='{'){
stack.push(c);
}else{
if(!stack.empty()){
char ch=stack.top();
stack.pop();
if(c==')' && ch!='(')
flag=false;
else if(c==']' && ch!='[')
flag=false;
else if(c=='}' && ch!='{')
flag=false;
}else
flag=false;
}
}
if(stack.size())
flag=false;
return flag;
}
};
法二:
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') st.push(')');
else if (s[i] == '{') st.push('}');
else if (s[i] == '[') st.push(']');
// 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
// 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
else if (st.empty() || st.top() != s[i]) return false;
else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
}
// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
return st.empty();
}
};
给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
法一:栈
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(char c:s){
if(!st.empty() && st.top()==c){
st.pop();
}else{
st.push(c);
}
}
string result = "";
while (!st.empty()) {
result += st.top();
st.pop();
}
reverse (result.begin(), result.end());
return result;
}
};
法二:字符串模拟栈
class Solution {
public:
string removeDuplicates(string S) {
string result;
for(char s : S) {
if(result.empty() || result.back() != s) {
result.push_back(s);
}
else {
result.pop_back();
}
}
return result;
}
};
class Solution {
public:
string removeDuplicates(string s) {
string res = "";
for(char c:s){
if(res.size() && res[res.size()-1]==c){
res.erase(res.size()-1,1);
}else{
res += c;
}
}
return res;
}
};
给你一个字符串数组 tokens ,表示一个根据 逆波兰表示法 表示的算术表达式。
请你计算该表达式。返回一个表示表达式值的整数。
注意:
1、有效的算符为 ‘+’、‘-’、‘*’ 和 ‘/’ 。
2、每个操作数(运算对象)都可以是一个整数或者另一个表达式。
3、两个整数之间的除法总是向零截断 。
4、表达式中不含除零运算。
5、输入是一个根据逆波兰表示法表示的算术表达式。
6、答案及所有中间计算结果可以用 32 位 整数表示。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stnum;
for(int i=0;i<tokens.size();i++){
if(tokens[i].size()>1 && tokens[i][0]=='-' || isdigit(tokens[i][0])){
stnum.push(stoi(tokens[i]));
}else{
if(stnum.size()>1){
int a=stnum.top();
stnum.pop();
int b=stnum.top();
stnum.pop();
if(tokens[i]=="+"){
stnum.push(a+b);
}else if(tokens[i]=="-"){
stnum.push(b-a);
}else if(tokens[i]=="*"){
stnum.push(b*a);
}else if(tokens[i]=="/"){
stnum.push(b/a);
}
}
}
}
return stnum.top();
}
};
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值 。
class Solution {
private:
class MyQueue { //单调队列(从大到小)
public:
deque<int> que; // 使用deque来实现单调队列
// 每次弹出的时候,比较当前要弹出的数值是否等于队列出口元素的数值,如果相等则弹出。
// 同时pop之前判断队列当前是否为空。
void pop(int value) {
if (!que.empty() && value == que.front()) {
que.pop_front();
}
}
// 如果push的数值大于入口元素的数值,那么就将队列后端的数值弹出,直到push的数值小于等于队列入口元素的数值为止。
// 这样就保持了队列里的数值是单调从大到小的了。
void push(int value) {
while (!que.empty() && value > que.back()) {
que.pop_back();
}
que.push_back(value);
}
// 查询当前队列里的最大值 直接返回队列前端也就是front就可以了。
int front() {
return que.front();
}
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MyQueue que;
vector<int> result;
for (int i = 0; i < k; i++) { // 先将前k的元素放进队列
que.push(nums[i]);
}
result.push_back(que.front()); // result 记录前k的元素的最大值
for (int i = k; i < nums.size(); i++) {
que.pop(nums[i - k]); // 滑动窗口移除最前面元素
que.push(nums[i]); // 滑动窗口前加入最后面的元素
result.push_back(que.front()); // 记录对应的最大值
}
return result;
}
};
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。
你可以按 任意顺序 返回答案。
法一:优先级队列(堆)
class Solution {
public:
// 小顶堆
class mycomparison {
public:
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {
return lhs.second > rhs.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
// 要统计元素出现频率
unordered_map<int, int> map; // map<nums[i],对应出现的次数>
for (int i = 0; i < nums.size(); i++) {
map[nums[i]]++;
}
// 对频率排序
// 定义一个小顶堆,大小为k
priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;
// 用固定大小为k的小顶堆,扫面所有频率的数值
for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) {
pri_que.push(*it);
if (pri_que.size() > k) { // 如果堆的大小大于了K,则队列弹出,保证堆的大小一直为k
pri_que.pop();
}
}
// 找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒序来输出到数组
vector<int> result(k);
for (int i = k - 1; i >= 0; i--) {
result[i] = pri_que.top().first;
pri_que.pop();
}
return result;
}
};
法二:通过vector数组排序
class Solution {
public:
static bool cmp(pair<int,int> p1,pair<int,int> p2){
return p1.second > p2.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int it:nums){
map[it]++;
}
vector<pair<int,int>> vec(map.begin(),map.end());
sort(vec.begin(),vec.end(),cmp);
vector<int> res;
for(int i=0;i<k;i++){
res.push_back(vec[i].first);
}
return res;
}
};
给你一个字符串 path ,表示指向某一文件或目录的 Unix 风格 绝对路径 (以 ‘/’ 开头),请你将其转化为更加简洁的规范路径。
在 Unix 风格的文件系统中,一个点(.)表示当前目录本身;此外,两个点 (…)表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。任意多个连续的斜杠(即,‘//’)都被视为单个斜杠 ‘/’ 。
对于此问题,任何其他格式的点(例如,‘…’)均被视为文件/目录名称。
请注意,返回的 规范路径 必须遵循下述格式:
1、始终以斜杠 ‘/’ 开头。 两个目录名之间必须只有一个斜杠 ‘/’ 。
2、最后一个目录名(如果存在)不能 以 ‘/’ 结尾。
3、此外,路径仅包含从根目录到目标文件或目录的路径上的目录(即,不含 ‘.’ 或 ‘…’)。
4、返回简化后得到的 规范路径 。
class Solution {
public:
string simplifyPath(string path) {
string ans;
int index=0;
string dir="";
vector<string> st;
path+='/';
while(index < path.size()){
char ch = path[index];
if(ch != '/'){
dir += ch;
index++;
continue;
}else if(dir==".." && !st.empty()){
st.pop_back();
}else if(dir!=".." && dir!="." && dir != ""){
st.push_back(dir);
}
dir="";
index++;
}
for(auto s:st){
ans+='/';
ans+=s;
}
return ans == "" ? "/" : ans;
}
};