The Largest Odd Number in String problem involves finding the largest odd number that can be formed as a substring of the given numeric string. An odd number ends with an odd digit (1, 3, 5, 7, 9).
class Solution {
public String largestOddNumber(String num) {
// Traverse the string from right to left
for (int i = num.length() - 1; i >= 0; i--) {
if ((num.charAt(i) - '0') % 2 != 0) {
// Return the substring from 0 to i (inclusive)
return num.substring(0, i + 1);
}
}
return ""; // No odd number found
}
}
O(N)
, where N
is the length of the string.O(1)
, as no additional space is used.Input: num = "35427"
Output: "35427"
Explanation:
- The entire string is odd because it ends with 7, which is odd.
Input: num = "4206"
Output: ""
Explanation:
- No odd number can be formed because the string ends with an even digit.