I am trying to solve the Valid Parentheses problem in Java (described here among other places: Valid Parentheses )
My code is as follows thus far:
class Solution {
public boolean isValid(String s) {
if(s.charAt(0) ="(") {
if(s.charAt(s.length-1) != ")"){
system.out.println("false");
}
}
if(s.charAt(0) ="[") {
if(s.charAt(s.length-1) != "]"){
system.out.println("false");
}
}
if(s.charAt(0) ="{") {
if(s.charAt(s.length-1) != "}"){
system.out.println("false");
}
}
}
}
Currently I am getting the following error:
Line 4: error: unexpected type
if(s.charAt(0) ="("){
Can anyone advise on what the issue is? I can't at the moment figure it out but feel like it's something simple I'm overlooking.
Two immediate issues:
char c = 'c';
==
. The single equals sign =
is used for assignment.So that line should be:
if(s.charAt(0) == '(') { /* ... */ }
Note that this only fixes the most immediate error you're experiencing. After fixing that, there are some more, for example system.out.println()
should be System.out.println()
.
And, after fixing that, I think you're still a way off from solving the actual assignment. Just keep at it & good luck!
There are some issues in your answer. Robby Cornelissen points you out some issues in his answer . And I also saw 2 errors in your code.
s.length
should be s.length()
. isValid
method.Issue 1
In the following statement, you are missing the brackets ()
after the length. Length is a method in Java that is used to get the length of a Java String that you know already.
if(s.charAt(s.length - 1) != ')')
So your above statement should be as follows.
if(s.charAt(s.length() - 1) != ')')
Issue 2
In your isValid
method it's returning a boolean
value. The return type of that method is boolean
. But you are not returning any boolean value inside your method. So you have to add a return statement. It may be,
return true;
or return false;
or any boolean variable
declared inside isValid
method.
it is best to use stack for valid parentheses in Java
class Solution {
public boolean isValid(String s) {
Stack stack = new Stack();
for(int i=0; i<s.length; i++){
if(s[i] =='('){
stack.push(')')
}
else if(s[i] == '['){
stack.push(']')
}
else if(s[i] =='{'){
stack.push('}')
}
else if(s[i] !== stack.pop()){
return false;
}
}
return true;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.