Longest subsequence with different adjacent characters | Java program for the above approach ; Function to find the longest subsequence with different adjacent character ; Length of the String s ; Previously picked character ; If the current character is different from the previous then include this character and update previous character ; Driver Code ; Function call
import java . util . * ; class GFG { static int longestSubsequence ( String s ) { int n = s . length ( ) ; int answer = 0 ; char prev = ' - ' ; for ( int i = 0 ; i < n ; i ++ ) { if ( prev != s . charAt ( i ) ) { prev = s . charAt ( i ) ; answer ++ ; } } return answer ; } public static void main ( String [ ] args ) { String str = " ababa " ; System . out . print ( longestSubsequence ( str ) ) ; } }