17330

How can I write a function boolean succeeds(char a, char b, String s)? using s.equals(“”), s.charAt(

Question:

I am trying to write a function that takes a string s and returns true if every occurrence of the character b is always succeeded by the character a, and false otherwise. I have tried:

boolean succeeds(char a, char b, String s) { boolean to_return = true; boolean seen_a = false; while(true) { if (s.equals("")) return to_return; char c2 = s.charAt(0); if (c2 == a) seen_a = true; if (c2 == b) { if (!seen_a) return false; } s = s.substring(1); } } }

I think I have the right idea. But I don't know how to put it together.

Answer1:

Given the guidelines, you can do something along the lines of

while (!s.equals("")) { char c = s.charAt(0); // record first char s = s.substring(1); // cut off first char // if "first char is 'b' and next is // not 'a'", we can return false if (c == b && (s.equals("") || s.charAt(0) != a)) return false; } return true; <hr />

By the way, this can be done much more easily:

return s.replace(""+b+a, "").indexOf(b) < 0;

(I just noticed that this approach was originally outlined in <a href="https://stackoverflow.com/questions/18111857/how-can-i-write-a-function-boolean-succeedschar-a-char-b-string-s-using-s-e/18111984#18111984" rel="nofollow">@JosephMyers' answer</a>)

Answer2:

This sounds like homework, so it's probably your responsibility to work out the details, but several suggestions keep coming to my mind, anyway.

For instance, you could try:

<ol><li>Remove all occurrences of "ba" in a temporary string.</li> <li>If no other letter(s) "b" remain in the temporary string, then return true.</li> <li>Otherwise return false.</li> </ol>

Hints: You can use the <a href="http://javarevisited.blogspot.com/2011/12/java-string-replace-example-tutorial.html" rel="nofollow">replace method</a> in step 1 and <a href="http://www.tutorialspoint.com/java/java_string_indexof.htm" rel="nofollow">indexOf</a> in step 2. (Click the links for tutorials/instructions You should be able to do this in two or three lines of code, depending on whether you use a ternary operator for the return value.)

Answer3:

It need not be so complex. For example:

for (i = 0; i < s.length - 1; i++) { if (s.charAt(i - 1) == b && s.charAt(i) != a) { return false; } } return !s.endsWith(String.valueOf(b));

Answer4:

Assuming you're limited to the functions you put in the title, and that you want to check if every b is followed by a (and not the other way around): you're halfway there, but your logic is a bit backwards. When you're going through the string:

(1) When you see "b", you will need to remember that fact. So you probably want a variable seen_b instead of seen_a.

(2) On the next character, if you remember that you just saw "b", you then need to make sure the next character is "a". So instead of

if (c2 == b) { if (!seen_a) return false; }

you probably should have something like

if (seen_b) { if (c2 != a) return false; }

or more concisely

if (seen_b && c2 != a) return false;

(3) Since seen_b==true means that the <em>last</em> character you saw is b, make sure you set it back to false every time you see something that isn't b.

(4) Make sure you do things right when the last character of the string is b. You have to return false because this isn't followed by "a".

Answer5:

Something like this should work. I have not compiled this. Hopefully it gets you in the right direction, even with possible syntax errors.

public boolean succeeds(char a, char b, String s){ boolean sawFirst= false; for(int i=0;i<s.length();i++){ if(!sawA){ if(s.charAt(i)==b) sawFirst = true; } else{ if(s.charAt(i)!=a) return false; else sawFirst= false; } } return true; }

Answer6:

using s.equals(“”), s.charAt(0), s.substring(1) ?

how about this:

public static boolean succeeds(final char a, final char b, String s) { if(s==null||s.equals("")) return true; char previousFirstChar,newFirstChar; previousFirstChar=s.charAt(0); while(true) { s=s.substring(1); if(s.equals("")) { if(previousFirstChar==b) return false; break; } newFirstChar=s.charAt(0); if(previousFirstChar==b && newFirstChar!=a)) return false; previousFirstChar=newFirstChar; } return true; }

Answer7:

Looking at your title, I'm unclear if you mean you <em>have</em> to use s.equals, .charAt, and .substring. However, if not, you can use a regular expression .*b[^a].*|.*b$ (thank you <strong>ajb</strong>) for this, where the function fails if it matches b followed by any character but a (or the special case b at the end of the string), e.g.:

import java.util.regex.Pattern; ... public boolean succeeds (char a, char b, String s) { String quoteda = Pattern.quote(Character.toString(a)); String quotedb = Pattern.quote(Character.toString(b)); return !(s.matches(".*" + quotedb + "[^" + quoteda + "].*|.*" + quotedb + "$")); }

Note that this will return true if the string doesn't contain a at all. If you want it to return false in that case, you'd have to check first:

public boolean succeeds (char a, char b, String s) { if (s.indexOf(b) == -1) return false; String quoteda = Pattern.quote(Character.toString(a)); String quotedb = Pattern.quote(Character.toString(b)); return !(s.matches(".*" + quotedb + "[^" + quoteda + "].*|.*" + quotedb + "$")); }

The reason we use Pattern.quote is to allow it to handle characters with special meaning in regular expressions, e.g. ']'.

If you <em>can't</em> use regular expressions, a state-machine style approach will give you good results:

public boolean succeeds (char a, char b, String s) { int state = 0; for (int n = 0; n < s.length(); ++ n) { if (state == 0) { if (s.charAt(n) == b) state = 1; } else if (state == 1) { if (s.charAt(n) == a) state = 0; else return false; } } return (state == 0); }

Since there's only two states you could just use a boolean.

Recommend

  • Covariant return type with non-pointer/reference return type
  • Extending enums
  • Is a collocated join (a-la-netezza) theoretically possible in hive?
  • A more compact representation than BASE64 for byte arrays?
  • Firebase Authentication Javascript: setCookie for pending Credential for redirect
  • Rounding returned float values from a DB to their 'correct' values
  • R replacing columns by lookup to dictionary
  • Request map direct me to Login page in Grails
  • Fastest way to save/load data.table
  • R matching more than 2 conditions and return the response value
  • Calling a second level base class constructor
  • Type mismatch: cannot convert from ListFragment to Fragment
  • How would I send and receive packets over a WebSocket in Javascript
  • removing the default blue color on focus
  • SSRS 2008 - Sorting within a group
  • replacing while loop with list comprehension
  • CSS Grid, position absolute an element in a css grid item: IMPOSSIBLE
  • Where these are stored?
  • Getting the scrolling offset when storing coordinates
  • Sending keystrokes/mouse clicks to a Java program with Autohotkey
  • DIV instruction jumping to random location?
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • How to match http request and response using Jersey ContainerRequestFilter and ContainerResponseFilt
  • With Hadoop, can I create a tasktracker on a machine that isn't running a datanode?
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Highlight one bar in a series in highcharts?
  • Master page gives error
  • Regex thinks I'm nesting, but I'm not
  • What is the “return” in scheme?
  • Different response to non-authenticated users and AJAX calls
  • Knitr HTML Loop - Some HTML output, some R output
  • R: gsub and capture
  • Calling of Constructors in a Java
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • Comma separated Values
  • Matrix multiplication with MKL
  • PHP: When would you need the self:: keyword?
  • How to disable jQuery.jplayer autoplay?
  • How to load view controller without button in storyboard?