Question:-
Write a program to get the string as input from the user and remove the duplicates. Then, sort the first half of the string in the descending order and the second half in the ascending order. If the String length is 7 consider the first 4 as the first half and next 3 as the second half.
Assumption: Only lowercase characters are allowed
Sample Input 1:
programming
Sample Output 1:
rpogaimn
Explanation:
1. programming -> progamin(After removing duplicates)
2. prog/amin ->rpog(Descending pattern) aimn(Ascending pattern)
3. ‘rpogaimn’ is the output for ‘programming’
Sample Input 2:
cake
Sample Output 2:
caek
Code:-
Main.java
import java.util.Scanner; import java.util.Arrays; import java.util.Collections; public class Main{ public static void main (String[] args) { Scanner sc = new Scanner(System.in); String input = sc.next(); int len = input.length(); String result = ""; for(int v = 0; v < len; v++) if(!result.contains(String.valueOf(input.charAt(v)))) result += String.valueOf(input.charAt(v)); char[] input_char = result.toCharArray(); char[] first_half, second_half; int length_of; if(input_char.length % 2 == 0){ length_of = input_char.length / 2; first_half = new char[input_char.length / 2]; second_half = new char[input_char.length / 2]; for(int i = 0; i < length_of; i++){ first_half[i] = input_char[i]; second_half[i] = input_char[i + length_of]; } } else{ length_of = input_char.length / 2; first_half = new char[length_of + 1]; second_half = new char[length_of]; for(int k = 0; k <= length_of; k++){ first_half[k] = input_char[k]; if(k != length_of) second_half[k] = input_char[k + length_of + 1]; } } Character[] first = new Character[first_half.length]; for(int n = 0; n < first_half.length; n++) first[n] = first_half[n]; Arrays.sort(first, Collections.reverseOrder()); Arrays.sort(second_half); for(int l = 0; l < first_half.length; l++) System.out.print(first[l]); for(int m = 0; m < second_half.length; m++) System.out.print(second_half[m]); } }
Recommended:-
- Array square
- Generate number using odd digits
- Alternate Number Difference
- Next Greatest number
- Mark Comparison
- Print the characters in descending order
- Vowels in a fishBowl
- Least offer
- Ascending and descending order
- Mail Domain
- Count repeating words
- Sentence – Convert to upper and lower
- Count consecutive repeating characters
- Zig zag Array
- Pass and Fail Count
- Search a Course
- Average and Grade Calculation
- String – Find and replace the character (first occurrence)
- Sort the first and second half of an array
- Retail Shop
- Palindrome
- Numerology
- InitCap
- Array Compatiblilty
- Sum of the maximum and the minimum element
- String Concatenation
- Find Average Age
- Login