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:

  1. Initialize an empty string numStr to store the extracted odd numbers.
  2. Iterate through the input string character by character.
  3. When a digit is encountered, append it to numStr.
  4. If a non-digit character is encountered and numStr is not empty, convert numStr to an integer, check if it's odd, and update the largest odd number if necessary. Reset numStr to an empty string.
  5. Repeat steps 2-4 until the end of the input string is reached.
  6. If numStr is 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.