LeetCode //C - 65. Valid Number

embedded/2024/11/13 16:02:40/

65. Valid Number

Given a string s, return whether s is a valid number.

For example, all the following are valid numbers: “2”, “0089”, “-0.1”, “+3.14”, “4.”, “-.9”, “2e10”, “-90E3”, “3e+7”, “+6e-1”, “53.5e93”, “-123.456e789”, while the following are not valid numbers: “abc”, “1a”, “1e”, “e3”, “99e2.5”, “–6”, “-+3”, “95a54e53”.

Formally, a valid number is defined using one of the following definitions:

  1. An integer number followed by an optional exponent.
  2. A decimal number followed by an optional exponent.

An integer number is defined with an optional sign ‘-’ or ‘+’ followed by digits.

A decimal number is defined with an optional sign ‘-’ or ‘+’ followed by one of the following definitions:

  1. Digits followed by a dot ‘.’.
  2. Digits followed by a dot ‘.’ followed by digits.
  3. A dot ‘.’ followed by digits.

An exponent is defined with an exponent notation ‘e’ or ‘E’ followed by an integer number.

The digits are defined as one or more digits.
 

Example 1:

Input: s = “0”
Output: true

Example 2:

Input: s = “e”
Output: false

Example 3:

Input: s = “.”
Output: false

Constraints:
  • 1 <= s.length <= 20
  • s consists of only English letters (both uppercase and lowercase), digits (0-9), plus ‘+’, minus ‘-’, or dot ‘.’.

From: LeetCode
Link: 65. Valid Number


Solution:

Ideas:

1. Flag Variables:

  • numSeen: This flag indicates whether at least one digit has been encountered in the string. It helps ensure there’s a valid numeric component in the string.
  • dotSeen: Tracks if a decimal point has been seen. This prevents multiple decimals which would invalidate the format.
  • eSeen: Indicates if an exponent character (e or E) has appeared, ensuring no repeated exponents and that the exponent is properly formatted.
  • numberAfterE: After an exponent is seen, this flag checks if a valid number follows. The presence of a number after the exponent is crucial for a valid scientific notation.

2. Initial Whitespace Handling:

  • The loop while (*s == ’ ') { s++; } moves the pointer s past any leading white spaces. Although the problem constraints do not mention spaces, handling them might make the function more generally applicable.

3. Character-by-Character Validation:

  • The for loop iterates through each character of the string:
    Digits: On encountering a digit, it sets numSeen to true and numberAfterE to true, indicating that there’s a valid number component.
    • Decimal Point (‘.’): Valid only if no previous decimal point or exponent has been seen (dotSeen or eSeen are false).
    • Exponent (‘e’ or ‘E’): Valid only if no previous exponent has been seen and there has been at least one digit before it. It sets eSeen to true and expects digits to follow (numberAfterE to false).
    • Signs (‘+’ or ‘-’): Signs are valid only at the beginning of the string or immediately following an exponent.
      Invalid Characters: Any character that is not a digit, a sign, a decimal point, or an exponent character leads to an immediate return of false.

4. Final Validity Check:

  • After exiting the loop, the function checks if at least one number has been seen (numSeen) and if a valid number follows any e or E (numberAfterE). This final validation ensures the overall string represents a valid number format.

5. Edge Case and Error Handling:

  • The function is designed to immediately reject strings upon encountering invalid scenarios, making it efficient in terms of runtime, especially for strings that fail early in the validation process.
Code:
bool isNumber(char* s) {// State flagsbool numSeen = false;bool dotSeen = false;bool eSeen = false;bool numberAfterE = true;// Trim leading whitespacewhile (*s == ' ') {s++;}// Process each characterfor (int i = 0; s[i] != '\0'; i++) {if (isdigit(s[i])) {numSeen = true;numberAfterE = true;} else if (s[i] == '.') {// There must not be a dot or 'e'/'E' already seenif (dotSeen || eSeen) {return false;}dotSeen = true;} else if (s[i] == 'e' || s[i] == 'E') {// There must not be an 'e'/'E' already seen and there must be a number before itif (eSeen || !numSeen) {return false;}eSeen = true;numberAfterE = false;} else if (s[i] == '+' || s[i] == '-') {// Sign must come after 'e' or 'E', or be at the startif (i > 0 && (s[i-1] != 'e' && s[i-1] != 'E')) {return false;}} else {// Invalid characterreturn false;}}// Trim trailing whitespacewhile (*s == ' ') {s++;}// Valid number if we've seen a number and if after 'e'/'E' there is also a numberreturn numSeen && numberAfterE;
}

http://www.ppmy.cn/embedded/33007.html

相关文章

java基于云计算的SaaS医院his信息系统源码 HIS云平台源码

目录 云HIS功能模块 1、预约挂号&#xff1a; 2、药库管理&#xff1a; 3、门诊医生站&#xff1a; 4、门诊费用&#xff1a; 5、药房管理&#xff1a; 6、治疗室&#xff08;门诊护士工作站&#xff09;&#xff1a; 7、统计分析&#xff1a; 8、财务管理&#xff1a;…

【1小时掌握速通深度学习面试4】图神经网络-上

目录 19.什么是图谱和图傅里叶变换? 20.以 GCN 为例&#xff0c;简述基于频谱域的图神经网络的发展 图卷积网络(GCN) GCN网络层数 小结笔记 19.什么是图谱和图傅里叶变换? 在数据的分析和统计应用中&#xff0c;数据往往呈现出非欧氏空间的复杂结构。它们不仅包含个体的…

web响应式页面是啥要注意啥

Web响应式页面是一种能够根据不同设备和屏幕尺寸自动调整布局、内容和功能的网页设计方式。这种设计方式的核心在于确保网页在各种平台上都能够正确显示和操作&#xff0c;为用户提供一致且良好的浏览体验。 在设计Web响应式页面时&#xff0c;有几个关键的注意事项&#xff1a…

60500 - Error 343 when transf. fixed assets w/o inv.support

错误消息 AA343“报废和接收资产在范围 xy 中具有差异投资代码”错误出现&#xff0c;即使不管理折旧范围 xy 中投资支持的固定资产将转移到管理此范围内投资支持的固定资产。 Tcode&#xff1a; AB01、ABUM 原因和前提条件 源代码检入过于严格。 解决方案 应用此notes

【Qt问题】VS2019 Qt win32项目如何添加x64编译方式

解决办法&#xff1a; 注意改为x64版本以后&#xff0c;要记得在项目属性里&#xff0c;修改Qt Settings、对应的链接include、lib等 参考文章 VS2019 Qt win32项目如何添加x64编译方式_vs2019没有x64-CSDN博客 有用的知识又增加了~

C++ STL

1. STL基本概念 1.1 STL六大组件 STL六大组件&#xff1a;容器、算法、迭代器、仿函数、适配器、空间适配器 2.4 STL中容器、算法、迭代器 2.5 容器算法 迭代器 2.5.1 vector存放内置数据类型 容器&#xff1a;vector 算法&#xff1a;for_each 迭代器&#xff1a;vector::it…

Rust web简单实战

一、使用async搭建简单的web服务 1、修改cargo.toml文件添加依赖 [dependencies] futures "0.3" tokio { version "1", features ["full"] } [dependencies.async-std] version "1.6" features ["attributes"]2、搭…

Java八股文3

3.垃圾回收 1.对象什么时候可以被垃圾器回收 1.垃圾回收的概念 为了让程序员更专注于代码的实现&#xff0c;而不用过多的考虑内存释放的问题&#xff0c;所以&#xff0c; 在Java语言中&#xff0c;有了自动的垃圾回收机制&#xff0c;也就是我们熟悉的GC(Garbage Collection)…