Largest Odd Number in String

To solve this problem, we can iterate the characters in the input string in reverse order. If we find an odd digit, we return the substring starting from index 0 to the current index+1. This will ensure that the returned substring is the largest odd number because it includes all the digits from the original number up to the first odd digit found from the right.

Here is the Python code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def largestOddNumber(self, num: str) -> str:
        # Iterate the characters in the input string in reverse order
        for i in range(len(num) - 1, -1, -1):
            # If the current character is an odd digit
            if int(num[i]) % 2 == 1:
                # Return the substring starting from index 0 to the current index+1
                return num[:i+1]

        # If there's no odd digit, return an empty string
        return ""

The for loop in the solution starts at the end of the string and ends at the beginning of it. When it finds the first odd digit (a digit whose modulo 2 equals 1), it returns a substring of num that goes from the first character (index 0) to the character at the current index + 1. If the loop ends without finding an odd digit, the function returns an empty string. This happens when all the digits in num are even.