Check if string follows order of characters defined by a pattern or not | Set 2 | C # program to check if characters of a string follow pattern defined by given pattern . ; Insert all characters of pattern in a hash set , ; Build modified string ( string with characters only from pattern are taken ) ; Remove more than one consecutive occurrences of pattern characters from modified string . ; After above modifications , the length of modified string must be same as pattern length ; And pattern characters must also be same as modified string characters ; Driver program
using System ; using System . Collections . Generic ; using System . Text ; class GFG { public static bool followsPattern ( String str , String pattern ) { HashSet < char > patternSet = new HashSet < char > ( ) ; for ( int i = 0 ; i < pattern . Length ; i ++ ) patternSet . Add ( pattern [ i ] ) ; StringBuilder modifiedString = new StringBuilder ( str ) ; for ( int i = str . Length - 1 ; i >= 0 ; i -- ) if ( ! patternSet . Contains ( modifiedString [ i ] ) ) modifiedString . Remove ( i , 1 ) ; for ( int i = modifiedString . Length - 1 ; i > 0 ; i -- ) if ( modifiedString [ i ] == modifiedString [ i - 1 ] ) modifiedString . Remove ( i , 1 ) ; if ( pattern . Length != modifiedString . Length ) return false ; for ( int i = 0 ; i < pattern . Length ; i ++ ) if ( pattern [ i ] != modifiedString [ i ] ) return false ; return true ; } public static void Main ( String [ ] args ) { String str = " engineers ▁ rock " ; String pattern = " er " ; Console . WriteLine ( " Expected : ▁ true , ▁ Actual : ▁ " + followsPattern ( str , pattern ) ) ; str = " engineers ▁ rock " ; pattern = " egr " ; Console . WriteLine ( " Expected : ▁ false , ▁ Actual : ▁ " + followsPattern ( str , pattern ) ) ; str = " engineers ▁ rock " ; pattern = " gsr " ; Console . WriteLine ( " Expected : ▁ false , ▁ Actual : ▁ " + followsPattern ( str , pattern ) ) ; str = " engineers ▁ rock " ; pattern = " eger " ; Console . WriteLine ( " Expected : ▁ true , ▁ Actual : ▁ " + followsPattern ( str , pattern ) ) ; } }