experchange > java

chad altenburg (02-17-20, 04:57 PM)
I *attempted* the following problem on codingbat.com while both high and drunk...

"
Given a string, return true if the number of appearances of "is" anywhere in the string is equal to the number of appearances of "not" anywhere in thestring (case sensitive).

equalIsNot("This is not") → false
equalIsNot("This is notnot") → true
equalIsNot("noisxxnotyynotxisi") → true
"

Here is what I came up with...

public boolean equalIsNot(String str) {
int numberIs = 0;
int numberNot = 0;
for (int i = 0 ; i <= str.length() - 2; i++) {
if (str.substring(i, i+2).equals("is") ) {
numberIs++;
}
}

for (int i = 0 ; i <= str.length() - 3; i++) {
if (str.substring(i, i+3).equals("not") ) {
numberNot++;
}
}
if (numberIs == numberNot) return true;
else return false;
}

And here is what I found via Google...



I don't know which one is more correct. With that, I going to back to listening to my neighbor's having loud sex.
Arne Vajhøj (02-17-20, 07:58 PM)
On 2/17/2020 9:57 AM, chad altenburg wrote:
(ignoring various non-Java pieces of information)> "
[..]
> And here is what I found via Google...
>
> I don't know which one is more correct.


They are pretty similar.

I believe there are at least 3 different approaches:
1) simple for loop and equals
2) a tricky loop and indexOf
3) regex

Arne
Joerg Meier (02-17-20, 11:48 PM)
On Mon, 17 Feb 2020 06:57:30 -0800 (PST), chad altenburg wrote:

> I *attempted* the following problem on codingbat.com while both high and drunk...


> "
> Given a string, return true if the number of appearances of "is" anywhere in the string is equal to the number of appearances of "not" anywhere in the string (case sensitive).


> equalIsNot("This is not") false
> equalIsNot("This is notnot") true
> equalIsNot("noisxxnotyynotxisi") true
> "


> Here is what I came up with...


Is that missing instructions ? Because otherwise, you can just do:

Function<String, Boolean> equalIsNot = s -> s.split("is", -1).length ==
s.split("not", -1).length;

Runnable example:

<https://repl.it/repls/ActiveAlertFactorial>

Liebe Gruesse,
Joerg
Similar Threads