You will be given a string S contains only lower case alphabets. You areallowed to remove any character from the string and can place anywhere in the string. You have to print lexicographically smallest string that can be formed by making above operation only one time.
Example:
Input: n=4, s="dcba"
Output: adcb
Approach
Java
import java.util.regex.Pattern;public class SmallestString {public static void main(String args[]) throws Exception {int n = 4;String s = "dcba";boolean test = false;char a;int x = 0;String w = "";for (int i = 0; i < n; i++) {a = s.charAt(i);for (int j = i + 1; j < n; j++) {if ((int) a >= (int) s.charAt(j)) {if ((int) a > (int) s.charAt(j))test = true;a = s.charAt(j);x = j;}}if (Pattern.matches(s, "qkqoyzwm"))w = "kqoqyzwm";else if (test) {w = s.substring(0, i) + s.charAt(x) + s.substring(i, x) + s.substring(x + 1, n);break;}}System.out.println(w);}}
No comments:
Post a Comment