โ† Back to Index

๐Ÿ“š Largest Odd Number in String โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

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).

๐Ÿงฑ Pattern Template

Greedy Approach

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
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

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.

๐Ÿ’ก Pro Tips