第五章 栈与队列part02
第五章 栈与队列**part02**
20. 有效的括号
Code :
class Solution {
public:
bool isValid(string s) {
stack<char> stack_Symbol ; // (what we really need do Now ) , 现在 需要 我们 往 前 上 , 要 做 xx , 而不是 xx
// 集中 力量
int i = 0;
//int len_s = s.length();
//for(i = 0 ; i < len_s ; i++)
for(i = 0 ; s[i] != '\0' ; i++)
{
if(stack_Symbol.empty())
{
stack_Symbol.push(s[i]);
}
else
{
char Cache_Char = stack_Symbol.top();
char Cache_Borther = Getborther(Cache_Char);
if(Cache_Borther == s[i])
{
stack_Symbol.pop();
}
else
{
stack_Symbol.push(s[i]);
}
}
}
if(stack_Symbol.empty())
{
return 1;
}
else
{
return 0;
}
}
char Getborther(char left)
{
switch(left)
{
case '(' :
return ')';
break;
case '{' :
return '}';
break;
case '[' :
return ']';
break;
};
return -1 ;
}
};
1047. 删除字符串中的所有相邻重复项
思路 : 在 使用 栈 储存 数据 后 , 想要 顺序 输出 数据 , -> 使用 另一个 栈(Cache 栈) 配合 (数据 倒着 放过去 , 再 倒 着 输出)
Code :
class Solution {
public:
string removeDuplicates(string s) {
stack<char> stack_Alphabet ;
stack<char> stack_Cache ;
//stack<char> stack_ConvertCache ;
int i = 0;
for( i = 0 ; s[i] != '\0' ; i++)
{
if(stack_Alphabet.empty())
{
stack_Alphabet.push(s[i]);
}
else
{
char alphabet_Top = stack_Alphabet.top();
if(alphabet_Top == s[i])
{
stack_Alphabet.pop();
}
else
{
stack_Alphabet.push(s[i]);
}
}
}
while(!stack_Alphabet.empty())
{
char Cache_Alphabet;
Cache_Alphabet = stack_Alphabet.top();
stack_Alphabet.pop();
stack_Cache.push(Cache_Alphabet);
}
i = 0 ;
//char * str_Receive ;
char * str_Receive = new char[20001] ;
while(!stack_Cache.empty())
{
str_Receive[i] = stack_Cache.top();
stack_Cache.pop();
i++;
}
str_Receive[i] = '\0';
return str_Receive;
}
};
150. 逆波兰表达式求值
注意 : 负数 检测 函数 段 不要 放 错 位置 了
Code :
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stack_Digit ;
// “新 据 点 ?”
//“逆波兰 表达 式”
//数字 压 栈 , 遇到 符号 , 提 数 (提 两个 数) , 计算 , 并 将 结果 压 栈
int len_tokens = tokens.size();
int num_Target;
int i = 0 ;
for( i = 0 ; i < len_tokens ; i++ )
{
//int num_Tag = Check_If_Operator(tokens[i]);
char num_Tag = Check_If_Operator(tokens[i]);
int Cache_Num;
int num2 ;
int num1 ;
int temp_Sum ;
//cout<<'+'<<endl;
//cout<<num_Tag<<endl;
// 代码 被 优化 了 ?
switch(num_Tag)
{
case '0' :
Cache_Num = stoi(tokens[i]);
stack_Digit.push(Cache_Num);
//cout<<"push "<<Cache_Num<<endl;
break ;
case '+' :
//case 1 :
num2 = stack_Digit.top();
stack_Digit.pop();
//cout<<"pop "<<num2<<endl;
num1 = stack_Digit.top();
stack_Digit.pop();
//cout<<"pop "<<num1<<endl;
temp_Sum = num1 + num2 ;
stack_Digit.push(temp_Sum);
//cout<<"push "<<temp_Sum<<endl;
//cout<<"temp_Sum = "<<temp_Sum<<endl;
break ;
case '-' :
//case 2 :
num2 = stack_Digit.top();
stack_Digit.pop();
//cout<<"pop "<<num2<<endl;
num1 = stack_Digit.top();
stack_Digit.pop();
//cout<<"pop "<<num1<<endl;
temp_Sum = num1 - num2 ;
stack_Digit.push(temp_Sum);
//cout<<"push "<<temp_Sum<<endl;
//cout<<"temp_Sum = "<<temp_Sum<<endl;
break ;
case '*' :
//case 3 :
num2 = stack_Digit.
