java - How can I write a function boolean succeeds(char a, char b, String s)? using s.equals(""), s.charAt(0), s.substring(1) -
i trying write function takes string s , returns true if every occurrence of character b succeeded character a, , false otherwise. 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 have right idea. don't know how put together.
given guidelines, can along lines of
while (!s.equals("")) { char c = s.charat(0); // record first char s = s.substring(1); // cut off first char // if "first char 'b' , next // not 'a'", can return false if (c == b && (s.equals("") || s.charat(0) != a)) return false; } return true;
by way, can done more easily:
return s.replace(""+b+a, "").indexof(b) < 0;
(i noticed approach outlined in @josephmyers' answer)
Comments
Post a Comment