Count of distinct possible strings after performing given operations | Java implementation of the above approach ; Function that prints the number of different strings that can be formed ; Computing the length of the given string ; Base case ; Traverse the given string ; If two consecutive 1 ' s ▁ ▁ or ▁ 2' s are present ; Otherwise take the previous value ; Driver code
import java . io . * ; class GFG { static void differentStrings ( String s ) { int n = s . length ( ) ; int [ ] dp = new int [ n + 1 ] ; dp [ 0 ] = dp [ 1 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s . charAt ( i ) == s . charAt ( i - 1 ) && ( s . charAt ( i ) == '1' || s . charAt ( i ) == '2' ) ) dp [ i + 1 ] = dp [ i ] + dp [ i - 1 ] ; else dp [ i + 1 ] = dp [ i ] ; } System . out . println ( dp [ n ] ) ; } public static void main ( String [ ] args ) { String S = "0111022110" ; differentStrings ( S ) ; } }