Q-8 Rearrange a string
Given a string containing uppercase alphabets and integer digits (from 0 to 9), the task is to print the alphabets in the lexicographical order followed by the sum of digits.
Example 1:
Input: S = "AC2BEW3"
Output: "ABCEW5"
Explanation: 2 + 3 = 5 and we print all
alphabets in the lexicographical order.
Example 2:
Input: S = "ACCBA10D2EW30"
Output: "AABCCDEW6"
Explanation: 0+1+2+3 = 6 and we print all
alphabets in the lexicographical order.
Your Task:
You don't need to read input or print anything. Your task is to complete the function arrangeString() which takes the string S as inputs and returns the modified string.
// { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GfG { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { String s = sc.next(); Solution obj = new Solution(); System.out.println(obj.arrangeString(s)); } } } // } Driver Code Ends //User function Template for Java
class Solution { public String arrangeString(String s) { //code here. ArrayList<String> arr = new ArrayList<>(); String[] str=s.split(""); int sum=0; String st=""; for(int i=0;i<str.length;i++) { if(str[i].matches("[0-9]")) sum+=Integer.parseInt(str[i]); else arr.add(str[i]); } Collections.sort(arr); for(int i=0;i<arr.size();i++) { st=st+arr.get(i); } st=st+Integer.toString(sum); return st; } }
Post a Comment
0 Comments