Longest substring consisting of vowels using Binary Search | Java implementation of the above approach ; Function to check if a character is vowel or not ; 0 - a 1 - b 2 - c and so on 25 - z ; Function to check if any subString of length k exists which contains only vowels ; Applying sliding window to get all subStrings of length K ; Remove the occurence of ( i - k + 1 ) th character ; Function to perform Binary Search ; Doing binary search on the lengths ; Driver Code
import java . util . * ; class GFG { static boolean vowel ( int vo ) { if ( vo == 0 vo == 4 vo == 8 vo == 14 vo == 20 ) return true ; else return false ; } static boolean check ( String s , int k ) { int [ ] cnt = new int [ 26 ] ; for ( int i = 0 ; i < k - 1 ; i ++ ) { cnt [ s . charAt ( i ) - ' a ' ] ++ ; } for ( int i = k - 1 ; i < s . length ( ) ; i ++ ) { cnt [ s . charAt ( i ) - ' a ' ] ++ ; int flag1 = 0 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( vowel ( j ) == false && cnt [ j ] > 0 ) { flag1 = 1 ; break ; } } if ( flag1 == 0 ) return true ; cnt [ s . charAt ( i - k + 1 ) - ' a ' ] -- ; } return false ; } static int longestSubString ( String s ) { int l = 1 , r = s . length ( ) ; int maxi = 0 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( check ( s , mid ) ) { l = mid + 1 ; maxi = Math . max ( maxi , mid ) ; } else r = mid - 1 ; } return maxi ; } public static void main ( String [ ] args ) { String s = " sedrewaefhoiu " ; System . out . print ( longestSubString ( s ) ) ; } }