Przejdź do głównej zawartości

String-2 > xyzThere - java

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. 


xyzThere("abcxyz") → true
xyzThere("abc.xyz") → false
xyzThere("xyz.abc") → true

Definiujemy loop ktory sprawdza za kazdym podejsciem czy kolejne indexy i,i+1 oraz i+2 i zdefiniowane dla nich char. 

Nalezy tu pamietac ze jesli sprawdamy po indeksach np i+2 to tzreba zostawic "miejsce" na koncu aby nie bylo outOfBoudnExeption tj przekroczenia rlugosci stringa.

Jezeli pierwszy warunek jest spelniony tj mamy na kolejnych indexach interesujace nas char-y sprawdzamy czy na poprzedzajacych nasza trojkę indexach pojawia sie "." zaczynamy od indexu 0 - tzreba to uwzglednić w warunku tj albo index 0 == 0 lub i-1 == 0


public boolean xyzThere(String str)
{
 int len = str.length() - 2;
 for(int i = 0; i < len; i++)
 {
  if(str.charAt(i) == 'x' && str.charAt(i+1) == 'y' && str.charAt(i+2) == 'z')
  {
   if(i == 0 || str.charAt(i-1) != '.')
    return true;
  }
 }
 return false;
}

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 )); }