LeetCode //C - 65. Valid Number

ops/2024/11/14 19:28:08/

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/ops/33990.html

相关文章

解决Git提交失败的问题:配置user.name和user.email

文章目录 一、场景描述二、原因分析三、解决办法1、全局配置2、单个项目配置3、验证配置 四、总结 在软件开发过程中&#xff0c;使用Git进行版本控制是必不可少的。然而&#xff0c;有时候在用Visual Studio Code提交代码时可能会遇到提交失败的情况&#xff0c;其中一个常见的…

第 10 场蓝桥杯小白入门赛题解

1.五一礼物【算法赛】 - 蓝桥云课 (lanqiao.cn) #include <iostream> using namespace std; int main() {cout<<"51"<<endl;return 0; }2.合成贤者之石【算法赛】 - 蓝桥云课 (lanqiao.cn) 假设黄水晶的个数是 x x x,那蓝水晶个数肯定是 x − 1 …

【hive】transform脚本

文档地址&#xff1a;https://cwiki.apache.org/confluence/display/Hive/LanguageManualTransform 一、介绍二、实现1.脚本上传到本地2.脚本上传到hdfs 三、几个需要注意的点1.脚本名不要写全路径2.using后面语句中&#xff0c;带不带"python"的问题3.py脚本Shebang…

关于YOLO8学习(一)环境搭建,官方检测模型部署到手机

一,环境的搭建 环境 win10 python 3.11 cmake pytorch pycharm 过程 首先安装好一个pycharm,这里就不一一叙述了。 其次,选择好一个python版本,是关键所在。有些YOLO的版本,并不支持很高的python版本,博主选用的是python3.11版本。经过实际的测试,这个版本比较合适。…

libhv http client vs cpr

libhv http client 和 cpr 的性能对比 libhv test code static void test_http_async(HttpClient* cli, int seq, int* resp_cnt) {auto req std::make_shared<HttpRequest>();req->method HTTP_GET;req->url "www.baidu.com";req->timeout 1…

libmodbus使用

安装可以看这个博客&#xff1a; https://blog.csdn.net/hanhui22/article/details/105786762 它的安装可以&#xff0c;但是编译测试看不太懂&#xff0c;我没跟着它的编译&#xff0c;完了后把/lib下的 放到开发板的/usr/lib下 编写代码: #include <stdio.h> #inclu…

【论文阅读】Sparse is Enough in Scaling Transformers

Sparse is Enough in Scaling Transformers 论文地址摘要1 介绍2 相关工作模型压缩。模型修剪模型蒸馏。稀疏注意力。张量分解。稀疏前馈。 3 Sparse is Enough3.1 稀疏前馈层3.2 稀疏 QKV 层3.3 稀疏损失层。 4 长序列的稀疏性4.1 长序列架构4.2 内存效率的可逆性4.3 泛化的循…

Servlet_JSP

1.一些回顾 对于Tomcat部署中 我们有一些补充的点需要在此说明一下 1.如果我们想要查询MINEType的话 可以到TOMCAT_HOME/conf/web.xml中进行查询 里面记录了不同类型对应的MINEType 2.我们客户端发送请求数据给服务器之后 服务器会调用父类中的service方法 然后在内部决定调用…