1、压缩算法 栈
class Solution {
public:
string compress(string str) {
stack<char> sta1, sta2;
for (int i = 0; i < str.length(); i++) {
if (str[i] != ']')
sta1.push(str[i]);
else {
while (sta1.top() != '|') {
sta2.push(sta1.top());
sta1.pop();
}
sta1.pop();
int num = 0,bit=0;
while (sta1.top() != '[') {
num += (sta1.top() - '0')*pow(10.0, bit++);
sta1.pop();
}
sta1.pop();
for (int i = 0; i < num; i++) {
stack<char> temp = sta2;
while (!temp.empty()) {
sta1.push(temp.top());
temp.pop();
}
}
while (!sta2.empty())
sta2.pop();
}
}
while (!sta1.empty()) {
sta2.push(sta1.top());
sta1.pop();
}
string res;
while (!sta2.empty()) {
res += sta2.top();
sta2.pop();
}
return res;
}
};
2、 楼高问题 左右看
public int[] findBuilding (int[] heights) {
// write code here
Stack<Integer> stack1 = new Stack<>();
int n = heights.length;
int[] res = new int[n];
Arrays.fill(res,1); //最起码能看到自己所在的这栋楼
for(int i=0;i<n-1;i++){ //首先向左边看
//只要当前楼大于等于前面遍历过的楼,就把前面的矮楼丢掉,因为我站在该楼右边是看不到的
while(!stack1.isEmpty() && heights[i]>=stack1.peek()){
stack1.pop();
}
stack1.push(heights[i]);
//这里i+1才是核心,因为我已经通过while循环把比当前楼矮的都去掉了,所以栈里剩下的都比当前楼高
//也就是说当我站在该楼的右边一栋楼,栈里的楼我都能看到
res[i+1]+=stack1.size();
}
Stack<Integer> stack2 = new Stack<>();
for(int i=n-1;i>0;i--){ //然后向右边看
while(!stack2.isEmpty() && heights[i]>=stack2.peek()){
stack2.pop();
}
stack2.push(heights[i]);
res[i-1]+=stack2.size(); //同理
}
return res;
}
3、范围覆盖问题
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, length;
cin >> n >> length;
vector<vector<int>> data;
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
data.push_back({ a,b });
}
sort(data.begin(), data.end());
if (data[0][0] > 0) {
cout<<"-1"<<endl;
return 0;
}
int res = 0, right = 0, i = 0;
while (i < n) {
int temp = right;
for (; i < n&&data[i][0] <= temp; i++)//逐个比较
right = max(right, data[i][1]);
res++;
if (right >= length) {//覆盖完全
cout << res << endl;
return 0;
}
if(i>=n||data[i][0]>right)
{cout<<"-1"<<endl;
return 0;}
}
return 0;
}