[Question]: In integer string Return the largest-valued odd integer (as a string) that is a non-empty substring of num
, or an empty string ""
if no odd integer exists.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: num = "52" Output: "5" Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number
input 25 – Op- 25.
input 4324 – Op- 43.
// TC: O(N)
// SC: O(N)
func largestOddNumber(_ num: String) -> String {
if num.isEmpty { return "" }
// #Approach #1: by iterating from last index Time limit exceed for large input
var last = num.count - 1
while last >= 0 {
let currentChar = String(num[num.index(num.startIndex, offsetBy: last)])
if Int(currentChar)! % 2 == 0 {
last -= 1
} else {// Re
let range = num.startIndex...num.index(num.startIndex, offsetBy: last)
return String(num[range])// return the all numbers from the odd index
}
}
return ""
// Approach #2 using clousers
// guard let i = num.lastIndex(where: { Int(String($0))! % 2 == 1 }) else { return "" }
// return String(num[...i])
}
let ipStr = "4324"
let opStr = largestOddNumber(ipStr)
print("op is ", opStr)//43