Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

trying to understand the code  RSS feed

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello guys!
here is the problem to solve : We'll say that a String is xy-balanced if for all the 'x' chars in the string, there exists a 'y' char somewhere later in the string. So "xxy" is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return true if the given string is xy-balanced.

xyBalance("aaxbby") → true
xyBalance("aaxbb") → false
xyBalance("yaaxbb") → false

here is the working solution:



please answer the Qs, written in the comments within the code. Thank you!
 
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"boolean" is a primitive datatype like "int". It can take the logical values of "true" or "false".

"&&" is a logical operator - it takes two parameters, and evaluates their logical "AND".

Here's the chapter in Oracle's tutorial that covers both these: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nah, that solution is not optimal (if it works -- I didn't even check).
Why not just check last index of 'x' (lastX).
If lastX < 0 that means 'x' is not present in a String so the String is balanced.
Else, get last index of 'y' (lastY).
If lastY > lastX return true,
else return false.
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dana Horst wrote:please answer the Qs, written in the comments within the code. Thank you!

Dana,

Please DontWriteLongLines. It makes your thread very hard to read, and it's actually bad coding practice.
I've broken yours up this time, but for future reference, please remember:
80 characters max.
(the SSCCE page actually recommends 62)
And that includes string literals and long method calls AND comments.

Thanks.

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!