current position:Home>411 stack and queue (20. valid parentheses, 1047. delete all adjacent duplicates in the string, 150. inverse Polish expression evaluation, 239. sliding window maximum, 347. the first k high-frequency elements)
411 stack and queue (20. valid parentheses, 1047. delete all adjacent duplicates in the string, 150. inverse Polish expression evaluation, 239. sliding window maximum, 347. the first k high-frequency elements)
2022-06-24 10:02:29【liufeng2023】
20. Valid parenthesis
class Solution {
public:
bool isValid(string s) {
stack<int> 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(']');
}
else if (st.empty() || st.top() != s[i])
{
return false;
}
else
{
st.pop();
}
}
return st.empty();
}
};
1047. Delete all adjacent duplicates in the string
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for (char s1 : s)
{
if (st.empty() || st.top() != s1)
{
st.push(s1);
}
else
{
st.pop();
}
}
string result = "";
while (!st.empty())
{
result += st.top();
st.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
150. Evaluate the inverse Polish expression
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (int i = 0; i < tokens.size(); i++)
{
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int num1 = st.top();
st.pop();
int num2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(num2 + num1);
if (tokens[i] == "-") st.push(num2 - num1);
if (tokens[i] == "*") st.push(num2 * num1);
if (tokens[i] == "/") st.push(num2 / num1);
}
else
{
st.push(stoi(tokens[i]));
}
}
int res = st.top();
st.pop();
return res;
}
};
239. Maximum sliding window
class Solution {
private:
class MyQueue {
// A monotonous queue ( From big to small )
public:
deque<int> que; // Use deque To implement monotonic queues
// Every time it pops up , Compare whether the current value to pop up is equal to the value of the queue exit element , Pop up if equal .
// meanwhile pop Judge whether the queue is currently empty .
void pop(int value) {
if (!que.empty() && value == que.front()) {
que.pop_front();
}
}
// If push The value of is greater than the value of the entry element , Then pop up the value at the back of the queue , until push The value of is less than or equal to the value of the queue entry element .
// This keeps the values in the queue monotonous, from large to small .
void push(int value) {
while (!que.empty() && value > que.back()) {
que.pop_back();
}
que.push_back(value);
}
// Query the maximum value in the current queue Directly return to the front of the queue, that is front That's all right. .
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++) {
// Before k Put the elements in the queue
que.push(nums[i]);
}
result.push_back(que.front()); // result Before recording k The maximum value of the element
for (int i = k; i < nums.size(); i++) {
que.pop(nums[i - k]); // Slide the window to remove the front most element
que.push(nums[i]); // Add the last element before sliding the window
result.push_back(que.front()); // Record the corresponding maximum value
}
return result;
}
};
347. front K High frequency elements
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int,int> mp;
vector<int> res;
for(int num : nums)
{
mp[num]++;
}
vector<pair<int,int>> vmp;
for(auto it = mp.begin(); it != mp.end(); it++)
{
vmp.push_back({
it->first, it->second});
}
sort(vmp.begin(), vmp.end(),
[](const pair<int, int>& x, const pair<int,int>& y)->int{
return x.second > y.second;});
for(int i = 0; i < k; i++)
{
res.push_back(vmp[i].first);
}
return res;
}
};
copyright notice
author[liufeng2023],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/202206240907453305.html
The sidebar is recommended
- Fasthttp: go framework ten times faster than net/http (server)
- The difference between preload and prefetch and how to optimize in webpack projects
- Several ways of calling methods to transfer parameters in react render
- Axios usage
- LabVIEW finds prime numbers in an array of n elements
- Elementui form custom regular expression validation text box
- Export markdown to HTML, PDF with browser
- Experience summary of typescript transformation process of old vue2.x projects
- Front end development uses graphql -- vue3 uses graphql
- JS to get the last element of the array
guess what you like
About Axios request - delete method
The salon for the first anniversary of the open source of oasis, an ant interactive graphics engine, is coming. On February 26, we will see you in the live studio!
Best practices for cookie notification
How does HTML5 implement live streaming? It's worth learning!
Record webpackdemo configuration
Android studio uses iconfont Ali vector icon library
HttpMediaTypeNotSupportedException: Content type ‘application. yml/json; charset=UTF-8‘ not supported
CSS notes
Nginx enables geoip2 module to realize national city identification - the road to dream
Database to query the quantity of books lent in this month. If it is higher than 10, it will display "more than 10 books lent in this month". Otherwise, it will display "less than 10 books lent in this month"
Random recommended
- Baidu map API User Guide - Javascript API | JavaScript API GL | JavaScript API Lite
- [javascript question brushing] tree - verify binary search tree, leetcode 98
- JavaScript gets the current date() and converts it to mm / DD / yyyy, June 23, 2022
- Explanation of HTTP network protocol
- Vue3+vite3 to develop Netease cloud music Day1 backend environment
- You can't even tell how nginx forwarded the request to you. It's good to say that you're not a crud Engineer?
- Baidu map JavaScript API, the earth mode is always similar to the "night mode", solve!
- Vue- different interfaces after different roles log in
- Bugatti launched a two wheeled scooter with less than 1000 US dollars
- The publishing function written by Vue (the simple version of wechat applet cooperates with cloud data development), pictures can be submitted, words can only be printed, but not submitted (self-improvement submission)
- Front end export excel, JS xlsx export
- Wed, front-end Personal Learning Websites
- The project cannot run after webpack installation
- Webpack dev server cannot start normally cannot find module 'webpack / bin / config yargs‘
- Ajax request request plug-in on uniapp for its own use
- Determine whether a function exists in JavaScript - function_ exists
- [bug] @jsonformat has a problem that the date is less than one day when it is used
- Vue/js operation DOM full screen switch, full screen open dom requestFullscreen();
- [angular] angular removes the input spaces. The angular user-defined attribute instruction - prohibits the input box from entering spaces - and deletes the spaces in the copied content (with other solutions attached)
- Cruise is now charging for its driverless ride service in San Francisco
- Principles of vue3 compiler
- Reactiveeffect principle of vue3
- Patch update details for vue3
- Nexttick principle of vue3
- Pyqt5 how to make windows borderless and movable by dynamically loading the UI?
- How to open an account online for new bonds? Please bless me
- React usestate storage function
- CSS problem, card jitter
- () is a linear table that restricts the internal structure of data elements to only one character. A. Stack B. queue C. string D. array
- Reactnative 0.69 release
- The new design can be called a new generation. The gradient borderless grille has a high appearance value. The application drawing of Changan Ruicheng plus
- Render external link address URL video page via iframe - Vue
- Vue failed to parse source for import analysis because the content contains invalid JS syntax
- Differences between front-end set and map
- Difference between front-end foreach and map
- Front end array flattening
- How the front end judges the data type
- Front end CSS style expand and collapse
- Front end array de duplication
- Front end throttling and anti shake