A strongest string

You are given a string S that consists of N lowercase letters of the Latin alphabet.
In one step, you can remove any letter in the string. You are required to determine the maximum lexicographic sentence of words you can leave so that all letters are different.

The lexicographical order on the set of all these finite words orders the words in the following manner:

  1. You are given two different words of the same length, for example, a=a1, a2, ...,ak and b=b1, b2, ..., bk. The order of these two words depends on the alphabetic order of the symbols on the first place i where the two words are different (counting from the beginning of the words), a<b if and only if ai<bi in the underlying order of alphabet A.
  2. If two words have different lengths, then the usual lexicographical order pads the shorter one with 'blanks' (a special symbol that is treated as smaller than every element of A) until the words are made of the same length. Now, the words are compared as in the previous case.

 

Example:

Input:  n=4, str="aybc"
Output: yc

Approach

Java

import java.util.ArrayList;
import java.util.HashMap;

public class StrongestString {
    public static void main(String args[]) {
        int n = 4;
        char s[] = "aybc".toCharArray();
        HashMap<CharacterArrayList<Integer>> hmap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            if (!hmap.containsKey(s[i])) {
                hmap.put(s[i], new ArrayList<>());
            }
            hmap.get(s[i]).add(i);
        }
        StringBuilder sb = new StringBuilder();
        int tmp = Integer.MIN_VALUE;
        for (char ch = 'z'; ch >= 'a'; ch--) {
            if (hmap.containsKey(ch)) {
                int len = hmap.get(ch).size();
                boolean flag = false;
                for (int i = 0; i < len; i++) {
                    if (flag == true)
                        break;
                    if (tmp < hmap.get(ch).get(i)) {
                        flag = true;
                        tmp = hmap.get(ch).get(i);
                        sb.append(ch);
                    }
                }
            }
        }
        System.out.println(new String(sb));
    }

}


No comments:

Post a Comment