You are given a string consisting of numeric digits (0-9) and Latin alphabetic characters ('a'-'z') only.
Your task is to sort the string but it must be sorted in a unique manner because here even characters or digits have higher priority than odd characters or digits. Although, as usual, other characters or digits have the same priority level. Also, digits have higher priority than characters.
Example:
Input: str="abcd1234"
Output: abcd1234
Approach
Java
public class UniqueSorting {public static void main(String args[]) {char arr[] = "abcd1234".toCharArray();int alphabets_odd[] = new int[26];int alphabets_even[] = new int[26];int numbers_odd[] = new int[10];int numbers_even[] = new int[10];StringBuilder sb = new StringBuilder();for (int i = 0; i < arr.length; i++) {if (arr[i] >= '0' && arr[i] <= '9') {int val = arr[i] - 48;if (val % 2 == 0)numbers_even[val]++;elsenumbers_odd[val]++;} else {int val = arr[i] - 97;if (val % 2 == 0)alphabets_even[val]++;elsealphabets_odd[val]++;}}for (int i = 1; i < alphabets_odd.length; i += 2) {char c = (char) (i + 97);for (int j = 0; j < alphabets_odd[i]; j++) {sb.append(c);}}for (int i = 0; i < alphabets_even.length; i += 2) {char c = (char) (i + 97);for (int j = 0; j < alphabets_even[i]; j++) {sb.append(c);}}for (int i = 1; i < numbers_odd.length; i += 2) {char c = (char) (i + 48);for (int j = 0; j < numbers_odd[i]; j++) {sb.append(c);}}for (int i = 0; i < numbers_even.length; i += 2) {char c = (char) (i + 48);for (int j = 0; j < numbers_even[i]; j++) {sb.append(c);}}sb.append('\n');System.out.print(sb.toString());}}
No comments:
Post a Comment