Repeated subsequence of length 2 or more | Java program to check if any repeated subsequence exists in the string ; A function to check if a string str is palindrome ; l and h are leftmost and rightmost corners of str Keep comparing characters while they are same ; The main function that checks if repeated subsequence exists in the string ; Find length of input string ; Create an array to store all characters and their frequencies in str [ ] ; Traverse the input string and store frequencies of all characters in freq [ ] array . ; If the character count is more than 2 we found a repetition ; In - place remove non - repeating characters from the string ; check if the resultant string is palindrome ; special case - if length is odd return true if the middle character is same as previous one ; It is checked so that StringIndexOutOfBounds can be avoided ; return false if string is a palindrome ; return true if string is not a palindrome ; Driver Code
class GFG { static int MAX_CHAR = 256 ; public static boolean isPalindrome ( String str , int l , int h ) { while ( h > l ) if ( str . charAt ( l ++ ) != str . charAt ( h -- ) ) return false ; return true ; } public static boolean check ( String str ) { int n = str . length ( ) ; int [ ] freq = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ str . charAt ( i ) ] ++ ; if ( freq [ str . charAt ( i ) ] > 2 ) return true ; } int k = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( freq [ str . charAt ( i ) ] > 1 ) str . replace ( str . charAt ( k ++ ) , str . charAt ( i ) ) ; str . replace ( str . charAt ( k ) , ' \0' ) ; if ( isPalindrome ( str , 0 , k - 1 ) ) { if ( ( k & 1 ) == 1 ) { if ( k / 2 >= 1 ) return ( str . charAt ( k / 2 ) == str . charAt ( k / 2 - 1 ) ) ; } return false ; } return true ; } public static void main ( String [ ] args ) { String str = " ABCABD " ; if ( check ( str ) ) System . out . println ( " Repeated ▁ Subsequence ▁ Exists " ) ; else System . out . println ( " Repeated ▁ Subsequence " + " ▁ Doesn ' t ▁ Exists " ) ; } }