Longest sub | PHP implementation to find the length of the longest sub$having frequency of each character less than equal to k ; function to find the length of the longest sub$ having frequency of each character less than equal to k ; hash table to store frequency of each table ; ' start ' index of the current substring ; to store the maximum length ; traverse the $ ' str ' ; get the current character as ' ch ' ; increase frequency of ' ch ' in ' freq [ ] ' ; if frequency of ' ch ' becomes more than ' k ' ; update ' maxLen ' ; decrease frequency of each character as they are encountered from the ' start ' index until frequency of ' ch ' is greater than ' k ' ; decrement frequency by '1' ; increment ' start ' ; update maxLen ; required length ; Driver Code
< ? php $ SIZE = 26 ; function longSubstring ( $ str , $ k ) { global $ SIZE ; $ freq = array ( ) ; for ( $ i = 0 ; $ i < $ SIZE ; $ i ++ ) $ freq [ $ i ] = 0 ; $ start = 0 ; $ maxLen = 0 ; $ ch = ' ' $ n = strlen ( $ str ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ ch = $ str [ $ i ] ; $ freq [ ord ( $ ch ) - ord ( ' a ' ) ] ++ ; if ( $ freq [ ord ( $ ch ) - ord ( ' a ' ) ] > $ k ) { if ( $ maxLen < ( $ i - $ start ) ) $ maxLen = $ i - $ start ; while ( $ freq [ ord ( $ ch ) - ord ( ' a ' ) ] > $ k ) { $ freq [ ord ( $ str [ $ start ] ) - ord ( ' a ' ) ] -- ; $ start ++ ; } } } if ( $ maxLen < ( $ n - $ start ) ) $ maxLen = $ n - $ start ; return $ maxLen ; } $ str = " babcaag " ; $ k = 1 ; echo ( " Length ▁ = ▁ " . longSubstring ( $ str , $ k ) ) ; ? >