Why do I get a wrong result? - string

Below are my codes for Leetcode 20. (Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.)
When the input is "(])" I still got true. Can anyone let me know what is wrong with my code? Thanks!
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(char c: s.toCharArray()){
if(c == '(' || c == '[' || c == '{'){
stack.push(c);
}else{
if(stack.empty()){
return false;
}
if(c == ')' && stack.peek() == '('){
stack.pop();
}
if(c == ']' && stack.peek() == '['){
stack.pop();
}
if(c == '}' && stack.peek() == '{'){
stack.pop();
}
}
}return stack.empty();
}
}

On the second iteration of the for loop you have char ], it doesn't match the first conditional so it goes on to the else block. None of the other if statements match, therefor it doesn't know what to do and just starts on the 3rd iteration of the loop, where it sees ) and also sees ( on peek so returns empty. This is where the issue lies. You'll need to add an additional else inside your else block to catch anything that doest match the 4 ifs.
In order to fix this particular test, add a check for the ] character only. if you see that character and you havent seen any [s then return false
Hopefully that helps, if not, let me know and I can try to clarify more.

Related

How to set an empty or not empty entry for a switch case statement?

I'd like to know to set an entry to validate if a String is empty or not empty in a switch-case statement. Let me show you:
String str = 'value'
switch(str){
case str == '':
println('Entered an empty value')
break
case str != '':
println('Entered value '+str)
break
case 'CoDe':
println('Entered special code '+str)
break
default:
println('Incorrect entry')
break
}
I know how to set an entry with a value (case 3) but I don't know how to set a entry with an empty or not empty string value.
Any help?
I tested it, and I think I have the answer for you.
switch(str) {
case "": // empty
println("Entered an empty value")
break
case "CoDe": // str == CoDe
println("Entered special code "+str)
break
default: // String not empty and not "CoDe"
println("Not empty")
break
}
It works because you have case "" which is the empty string. Meaning that everithing else is not empty. everything else is the default:
If you are not convinced, I'll give you a different example with the same meaning.
if (str.isEmpty()) {
// do something
} else if (!str.isEmpty()) { // <- this if is redundant
// do something else
}
You don't need the second if, because, you enter the else branch only if str is not empty! I appleid the same logic to the case. And it works because case "": in Java is valid.
As commented, what you need in Java is a series of if tests.
In the String class, you can test either:
The string has no characters at all (isEmpty)
The string has no characters OR has only whitespace characters (isBlank)
if ( str.isEmpty() ) { System.out.println( "ERROR - String has no characters." ); }
else if ( str.isBlank() ) { System.out.println( "ERROR - String has only whitespace." ); }
else if ( str.equals( "CoDe" ) ) { System.out.println( "Code received." ); }
else { System.out.println( "ERROR - Incorrect entry." ); }
See that code run live at Ideone.com.
Before that code block, I would add a null-check.
Objects.requireNonNull( str ); // Throw exception if null.
I find the if - else if - else construct in Java to be awkward in terms of readability. The switch syntax is much better at making obvious that a series of possibilities is being tested, mutually-exclusive, with a single result.
I do wish Java offered a cascading test for a series of boolean expressions. I have used such a feature in another language. There I found the cascading-boolean-tests to be quite practical for handling a series of business rules. But, alas, no such feature in Java. If only Brian Goetz were taking my calls.
I do not know Groovy. Perhaps Groovy provides another facility.
Your code has a smell, as str != '' would block all further cases.
I would re-organize it and use straight-forward basic Groovy switch-statement:
String str = 'value'
switch(str){
case 'CoDe':
println "Entered special code $str"
break
case '':
println 'Entered an empty value'
break
case { str != '' && str != null }:
println "Entered value $str"
break
default:
println 'Incorrect entry'
}
prints
Entered value value

Space and other character does gets counted

Every single time I run this program I get the number of vowels and consonants only
gets counted the number of spaces and any other special characters are not counted
I can't seem to figure out what is wrong in my code.
Does anybody have the solution to this?
void vowel_consonant(char *c)
{
int i,vcount,ccount,scount,ocount;
vcount=ccount=scount=ocount=0;
for (i=0;c[i]!='\0';i++)
{
if((c[i]=='a'||c[i]=='e'||c[i]=='i'||c[i]=='o'||c[i]=='u')||(c[i]=='A'||c[i]=='E'||c[i]=='I'||c[i]=='O'||c[i]=='U'))
vcount++;
else if((c[i]>=65 || c[i]<=90) && (c[i]>=97 || c[i]<=122))
ccount++;
else if(c[i]==' ')
scount++;
else
ocount++;
}
cout<<"Number of vowels:"<<vcount<<endl;
cout<<"Number of consonant:"<<ccount<<endl;
cout<<"Number of space:"<<scount<<endl;
cout<<"Number of extra:"<<ocount<<endl;
}

what can I do to my code donĀ“t delete a 0 in a array?

I'm trying to make a calculator in Haxe, it is almost done but have a bug. The bug is happening every time that some part of the equation result in 0.
This is how I concatenate the numbers and put i the array number, the cn is the variable used to receive the digit and transform in a number, the ci is a specific counter to make the while work well and the c is the basic counter that is increased to a background while used to read the array (input) items:
var cn = '';
var ci = c;
if (input[c] == '-') {
number.push('+');
cn = '-';
ci ++;
}
while (input[ci] == '0' || input[ci] == '1' || input[ci] == '2' || input[ci] == '3' || input[ci] == '4' || input[ci] == '5' || input[ci] == '6' || input[ci] == '7' || input[ci] == '8' || input[ci] == '9' || input[ci] == '.') {
if(ci == input.length) {
break;
}
cn += input[ci];
ci++;
}
number.push(cn);
c += cn.length;
This is the part of the code used to calculate the addition and subtraction
for (i in 0 ... number.length) { trace(number); if (number[c] == '+') { number[c-1] = ''+(Std.parseFloat(number[c-1])+Std.parseFloat(number[c+1])); number.remove(number[c+1]); number.remove(number[c]); }
else {
c++;
}
}
Example:
12+13-25+1: When my code read this input, it transform in a array ([1,2,+,1,3,-,2,5,+,1]), then the code concatenate the numbers ([12,+,13,-,25,+,1]) and for lastly it seeks for the operators(+,-,* and /) to make the operation (ex: 12+13), substituting "12" for the result of the operation (25) and removing the "+" and the "13". This part works well and then the code does 25-25=0.
The problem starts here because the equation then becomes 0+1 and when the code process that what repend is that the 0 vanish and the 1 is removed and the output is "+" when the expected is "1".
remove in this case uses indexOf and is not ideal, suggest using splice instead.
number.splice(c,1);
number.splice(c,1);
https://try.haxe.org/#D3E38

Checking for non terminating block statements in a file

I am working on a project that wants me to check for multi comments in a text file and also to see if it is a non terminating block statements. Pretty much I am using get char to check each character and compare it to the multi comment symbols and use peek to see if the next character matches the other symbols. The first part is working but to know when there is no terminating block statements is confusing please help.
if (c == '#' && inFile.peek() == '|') {
char next = '\0';
multipleComment += c;
while (inFile.get(c)) {
next = inFile.peek();
multipleComment += c;
if (c == '\n')
lineNumber++;
if (c == '|' && next == '#')
{
multipleComment += next;
tokenTypes.push_back(multipleComment);
values.push_back("COMMENT");
lineNumbers.push_back(lineNumber);
multipleComment.clear();
break;
}
else {
values.push_back("UNDEFINED");
tokenTypes.push_back(text);
lineNumbers.push_back(lineNumber);
}
}
}

Remove surrounding double or single quotes in Golang

Shouldn't strconv.Unquote handle both single and double quotes?
See also https://golang.org/src/strconv/quote.go - line 350
However following code returns a syntax error:
s, err := strconv.Unquote(`'test'`)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(s)
}
https://play.golang.org/p/TnprqhNdwD1
But double quotes work as expected:
s, err := strconv.Unquote(`"test"`)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(s)
}
What am I missing?
There is no ready function for what you want in the standard library.
What you presented works, but we can make it simpler (and likely more efficient):
func trimQuotes(s string) string {
if len(s) >= 2 {
if c := s[len(s)-1]; s[0] == c && (c == '"' || c == '\'') {
return s[1 : len(s)-1]
}
}
return s
}
Testing it:
fmt.Println(trimQuotes(`'test'`))
fmt.Println(trimQuotes(`"test"`))
fmt.Println(trimQuotes(`"'test`))
Output (try it on the Go Playground):
test
test
"'test
strconv.Unquote does properly handle both single and double quotes, but it isn't intended to be used in the way that your code snippet invokes it. It's intended for use in cases where you are processing go source code, and come across a string literal. The single quote case is valid for a single character, and not a string. In your go source files, if you try to use single quotes for a multi-character string literal, you'll get a compiler error similar to illegal rune literal.
What you can do instead for removing quotes from the start and end of a string, is use the strings.Trim function to take care of it.
s := strings.Trim(`'test'`, `'"`)
fmt.Println(s)
Temp workaround:
func trimQuotes(s string) string {
if len(s) >= 2 {
switch {
case s[0] == '"' && s[len(s)-1] == '"':
return s[1 : len(s)-1]
case s[0] == '\'' && s[len(s)-1] == '\'':
return s[1 : len(s)-1]
}
}
return s
}

Resources