[LeetCode] 1903. Largest Odd Number in String

You are given a string num, representing a large integer. 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.

Example 2:
Input: num = "4206"
Output: ""
Explanation: There are no odd numbers in "4206".

Example 3:
Input: num = "35427"
Output: "35427"
Explanation: "35427" is already an odd number.

Constraints:
1 <= num.length <= 105
num only consists of digits and does not contain any leading zeros.

字符串中的最大奇数。

给你一个字符串 num ,表示一个大整数。请你在字符串 num 的所有 非空子字符串 中找出 值最大的奇数 ,并以字符串形式返回。如果不存在奇数,则返回一个空字符串 "" 。
子字符串 是字符串中的一个连续的字符序列。

思路

思路是贪心。因为只允许删除字符,但是从左往右删除字符是无法改变数字的奇偶性的,所以思路是从右往左遍历 input 字符串,看看最右边一个字符串到底是奇数还是偶数。如果是奇数就可以直接返回了;如果是偶数,则删除当前字符,接着看左边的字符。

复杂度

时间O(n)
空间O(1)

代码

Java实现

class Solution {
public String largestOddNumber(String num) {
int n = num.length();
for (int i = n - 1; i >= 0; i--) {
int d = num.charAt(i) - '0';
if (d % 2 == 1) {
String str = num.substring(0, i + 1);
return str;
}
}
return "";
}
}
posted @   CNoodle  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示