我是一个新的学习者并试图解决Leetcode上的问题,但是有一个编译错误.
public class Solution
{
public bool IsValid(string s)
{
if(s.Length%2==1)
{
return false;
}
if(s.Length==0)
{
return true;
}
Stack st=new Stack();
for(int i=0;i<s.Length;i++)
{
switch(s[i])
{
case '(':
st.Push(s[i]);
break;
case'[':
st.Push(s[i]);
break;
case'{':
st.Push(s[i]);
break;
case ')':
if(st.Count==0||st.Peek()!='(')
{
return false;
}
else
{
st.Pop();
}
break;
case']':
if(st.Count==0||st.Peek()!='[')
{
return false;
}
else
{
st.Pop();
}
break;
case'}':
if(st.Count==0||st.Peek()!='}')
{
return false;
}
else
{
st.Pop();
}
break;
}
}
return st.Count==0;
}
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误.
第28行:运算符'!='不能应用于'object'和'char'类型的操作数
可能就是这个
if(st.Count==0||st.Peek()!='(')
Run Code Online (Sandbox Code Playgroud)
我知道这是关于数据类型的,但我不知道如何解决它.
我不是说英语的人,所以我的一些英语语法可能会疯狂.对不起,感谢您能帮助我.
小智 12
Stack
存储对象,但您想要char
专门存储.请改用Stack <char>.
Stack<char> st = new Stack<char>();
Run Code Online (Sandbox Code Playgroud)