Return previous element in an expanding matrix | Java program to return previous element in an expanding matrix ; Returns left of str in an expanding matrix of a , b , c and d . ; Start from rightmost position ; If the current character is b or d , change to a or c respectively and break the loop ; If the current character is a or c , change it to b or d respectively ; driver program to test above method
import java . io . * ; class GFG { static StringBuilder findLeft ( StringBuilder str ) { int n = str . length ( ) ; while ( n > 0 ) { n -- ; if ( str . charAt ( n ) == ' d ' ) { str . setCharAt ( n , ' c ' ) ; break ; } if ( str . charAt ( n ) == ' b ' ) { str . setCharAt ( n , ' a ' ) ; break ; } if ( str . charAt ( n ) == ' a ' ) str . setCharAt ( n , ' b ' ) ; else if ( str . charAt ( n ) == ' c ' ) str . setCharAt ( n , ' d ' ) ; } return str ; } public static void main ( String [ ] args ) { StringBuilder str = new StringBuilder ( " aacbddc " ) ; System . out . print ( " Left ▁ of ▁ " + str + " ▁ is ▁ " + findLeft ( str ) ) ; } }