Leetcode 2384 Largest Palindromic Number Solution in Java | Hindi Coding Community

0

 



You are given a string num consisting of digits only.

Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes.

Notes:

  • You do not need to use all the digits of num, but you must use at least one digit.
  • The digits can be reordered.

 

Example 1:

Input: num = "444947137"
Output: "7449447"
Explanation: 
Use the digits "4449477" from "444947137" to form the palindromic integer "7449447".
It can be shown that "7449447" is the largest palindromic integer that can be formed.

Example 2:

Input: num = "00009"
Output: "9"
Explanation: 
It can be shown that "9" is the largest palindromic integer that can be formed.
Note that the integer returned should not contain leading zeroes.

 

Constraints:

  • 1 <= num.length <= 105
  • num consists of digits.
Java Code :



public String largestPalindromic(String num) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i=0;i<num.length();i++){
int value = num.charAt(i) - '0';
hm.put(value,hm.getOrDefault(value,0)+1);
}
StringBuilder sb = new StringBuilder();
StringBuilder rev = new StringBuilder();
while(true){
boolean flag = false;
for(int i=9;i>=0;i--){
if(sb.length() == 0 && i == 0) continue;
int freq = hm.getOrDefault(i,0);
if(freq != 0){
if(freq%2 == 0){
for(int j=1;j<=freq/2;j++){
sb.append(i);
rev.append(i);
flag = true;
}
hm.put(i,0);
}
else{
int value = freq/2;
int mod = freq%2;
for(int j=1;j<=value;j++){
sb.append(i);
rev.append(i);
flag = true;
}
hm.put(i,mod);
}
}
}
if(!flag) break;
}
for(int i=9;i>=0;i--){
if(hm.containsKey(i) && hm.get(i)>0){
sb.append(i);
break;
}
}
String str = (sb.toString() + rev.reverse().toString());
return str;
}



Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !