Przejdź do głównej zawartości

String-2 > xyBalance

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

Szukam char i rownego x, nastepnie musimy spwardzic czy po tym x jest y tj generujemy string i drugi warunek ten substring zaczyna sie od i w ktorym zostal odnotowany x i jedzie do konca szukajac y - jesli true to oba true jesli false wtedy false


public boolean xyBalance(String str) {
  for (int i=0; i<str.length();i++){
  if (str.charAt(i)=='x'){
    if (
      str.substring(i+1,str.length()).contains("y")&& 
      str.charAt(str.length()-1)!='x'){
        return true;
        
      }return false;
    
  }
}return true;
}

Eleganckie rozwiązanie z dodatkową zmienną  i loopem iterujacym od konca - to zalatwia problem gdy x jest na koncu jesli x jest na koncu a od tego zaczynamy loopa na dzien dobry dostajemy false


public boolean xyBalance(String str)
{
 int len = str.length() - 1;
 char ch;
 for(int i = len; i >= 0; i--)
 {
  ch = str.charAt(i);
  if(ch == 'x')
   return false;
  else if(ch == 'y')
   return true;
 }
 return true;  
}

Komentarze

Popularne posty z tego bloga

Skrócony zapis if - instrukcja warunkowa java

Instrukcja warunkowa - warunek i rezultat. if (warunek) { jesli spełniony wykonań operacje i zwróć wynik; } warunek nie spełniony Możliwości skrócenia kodu instrukcji warunkowej if (i < 0) ? i-- : i++; Jeżeli i mniejsze od zera to i-- jezeli false to i++ if (i < 0) {     i--; } else {     i++; } Skrócony zapis instrukcji warunkowej else if (i < 0) ? i--;  inna_zmienna=4; : i++; if (i < 0) {     i--; } else {     i++;     inna_zmienna = 4; } Skrócony zapis if

String-1 > endsLy

Given a string, return true if it ends in "ly". endsLy("oddly") → true endsLy("y") → false endsLy("oddy") → false public boolean endsLy ( String str ) { if ( str . length ()< 2 ){ return false ; } if (( str . substring ( str . length ()- 2 , str . length ())). equals ( "ly" )){ return true ; } return false ; }

String-1 > withouEnd2

Given a string, return a version without both the first and last char of the string. The string may be any length, including 0. withouEnd2("Hello") → "ell" withouEnd2("abc") → "b" withouEnd2("ab") → "" public String withouEnd2 ( String str ) { if ( str . length ()== 1 ){ return str . substring ( 1 ); } else if ( str . length ()== 0 ){ return str ; } return ( str . substring ( 1 , str . length ()- 1 )); }