[英]C#: Operator '!=' cannot be applied to operands of type 'object' and 'char'
I am a new learner and trying to solve a problem on the Leetcode, but there was a compile error. 我是一名新手,正在尝试解决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;
}
}
I get an error. 我得到一个错误。
Line 28: Operator '!=' cannot be applied to operands of type 'object' and 'char'
第28行:运算符'!='不能应用于类型'object'和'char'的操作数
Might be this one 可能是这个
if(st.Count==0||st.Peek()!='(')
I know this is about datatype, but I don't know how to solve it. 我知道这与数据类型有关,但是我不知道如何解决它。
I am not an English speaker so some of my English grammar might be crazy. 我不是讲英语的人,所以我的一些英语语法可能有些疯狂。 Sorry about that, and thank you if you can help me.
抱歉,谢谢您的帮助。
Stack
stores objects, but you want to store char
specifically. Stack
存储对象,但是您要专门存储char
。 Use Stack<char> instead. 请改用Stack <char> 。
Stack<char> st = new Stack<char>();
You are getting the error because you are using a Stack without generics. 之所以会出现错误,是因为您使用的是不带泛型的堆栈。 Your stack is a stack of type
Object
. 您的堆栈是
Object
类型的堆栈。
You would need to cast the data you pop or peek from your stack to char
. 您需要将从堆栈中弹出或查看的数据转换为
char
。
example: 例:
if(st.Count==0|| (char) st.Peek()!='(')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.