Longest Subsequence of a String

Longest Subsequence of a string is the longest chronological sequence of the characters in a string. For example, if “abcdggabcdeggabcdefghifklmabc” is a string then the longest subsequence of that string is, “abcdggabcdeggabcdefghifklmabc”. The following code shows how to find it using java.

public class LongestSubsequence {
    StringBuffer sub_sequ = new StringBuffer();
    List<String> sub_sequences = new ArrayList<>();
    int index = 0;
    public List<String> sequence(String s) {
        for (int i = 0; i < s.length(); i++) {
            for (char j = 'a'; j <= 'z'; j++, i++) {
                if (s.charAt(i) == j) {
                    sub_sequ.append(s.charAt(i));
                } else {
                    break;
                }
            }
            sub_sequences.add(index, sub_sequ.toString());
            sub_sequ.delete(0,sub_sequ.length());
        }
        sub_sequences.removeAll(Arrays.asList("",null));
        return sub_sequences;
    }
    

    public String longestSubsequence(List<String> sub_sequences) {
       Collections.sort(sub_sequences);
       return sub_sequences.get(sub_sequences.size()-1);
    } 
}

Author: ashiquechowdhury

A software developer, and a data science enthusiast

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s