712068. Largest odd number in string
Easy
Largest odd number in string
Summary
Given a string, find the largest odd number contained within it. The numbers in the string can be separated by any characters (spaces, punctuation, etc.). For example, if the input is "hello 123 world 456", the output should be 457.
Detailed Explanation
The approach to solve this problem is straightforward. We iterate through the string and extract all the odd numbers from it. Then, we compare these odd numbers to find the largest one. Here's a step-by-step breakdown of the solution:
- Initialize an empty string
numStrto store the extracted odd numbers. - Iterate through the input string character by character.
- When a digit is encountered, append it to
numStr. - If a non-digit character is encountered and
numStris not empty, convertnumStrto an integer, check if it's odd, and update the largest odd number if necessary. ResetnumStrto an empty string. - Repeat steps 2-4 until the end of the input string is reached.
- If
numStris not empty at the end, convert it to an integer and update the largest odd number if necessary.
The time complexity of this solution is O(n), where n is the length of the input string, because we're iterating through the string once. The space complexity is also O(n) for storing the extracted numbers.
Optimized Solutions
Java
public int largestOddNumber(String s) {
int max = 0;
StringBuilder numStr = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
numStr.append(c);
} else if (!numStr.toString().isEmpty()) {
int num = Integer.parseInt(numStr.toString());
if (num % 2 != 0 && num > max) {
max = num;
}
numStr = new StringBuilder();
}
}
if (!numStr.toString().isEmpty()) {
int num = Integer.parseInt(numStr.toString());
if (num % 2 != 0 && num > max) {
max = num;
}
}
return max;
}