![]() |
VOOZH | about |
Given a string s, representing a non-negative integer, return the largest-valued odd integer (as a string) that is a substring of the given string s. If no such odd-valued substring exists, return an empty string ("").
Examples:
Input: s = "504"
Output: "5"
Explanation: The only substring "5" is an odd number.Input: s = "2042"
Output: ""
Explanation: All the possible non-empty substrings have even values.
Table of Content
The idea is to generate all possible substrings of the given string and check whether each substring represents an odd number. A number is odd if its last digit is odd. Among all valid substrings, we keep the maximum-valued one.
5
The key idea is that a number is odd only if its last digit is odd (1, 3, 5, 7, 9). Therefore, to obtain the largest-valued odd substring, we find the rightmost odd digit in the string and return the prefix of the string ending at that index.
Consider string : s = "504"
Step 1: Traverse the string from index n-1 to 0 to find the first odd digit.
Step 2: Check characters
Step 3: First odd digit is found at index 0, so we return: S[0...0] = "5"
5