← Home

65. Valid Number

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
65

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 65. Valid Number, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are trim_left, trim_right, trim_all, isPosNegCorrect, isNumber.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Valid Number.
02//Memory Usage: 6.1 MB, less than 36.30% of C++ online submissions for Valid Number.
03class Solution {
04public:
05    static inline void trim_left(std::string &s) {
06        s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
07            return !std::isspace(ch);
08        }));
09    }
10
11    // trim from end (in place)
12    static inline void trim_right(std::string &s) {
13        s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
14            return !std::isspace(ch);
15        }).base(), s.end());
16    }
17
18    // trim from both ends (in place)
19    static inline void trim_all(std::string &s) {
20        trim_left(s);
21        trim_right(s);
22    }
23    
24    bool isPosNegCorrect(string& s){
25        //check if the count and pos of '+' or '-' is correct
26        //this function also remove '+' and '-' for later process
27        if(s == "+" || s == "-") return false;
28        int pos_count = count(s.begin(), s.end(), '+');
29        int neg_count = count(s.begin(), s.end(), '-');
30        if(pos_count > 1) return false;
31        if(neg_count > 1) return false;
32        if(pos_count + neg_count > 1) return false;
33        
34        int pos;
35        if((pos = s.find('+')) != string::npos &&  pos > 0) return false;
36        if((pos = s.find('-')) != string::npos &&  pos > 0) return false;
37        
38        if(s[0] == '+') s.erase(0,1);
39        if(s[0] == '-') s.erase(0,1);
40        
41        return true;
42    }
43    
44    bool isNumber(string s) {
45        //remove spaces
46        trim_all(s);
47        //" " is invalid
48        if(s.empty()) return false;
49        
50        //contains something not in 0-9, "e", "+", "-", "."
51        if(!s.empty() && s.find_first_not_of("0123456789e+-.") != string::npos)
52            return false;
53        
54        //process and remove 'e'
55        int e_count;
56        if((e_count = count(s.begin(), s.end(), 'e')) > 1) return false;
57        
58        string s_before_e, s_after_e;
59        
60        if(e_count == 1){
61            int pos = s.find('e');
62            s_before_e = s.substr(0, pos);
63            s_after_e = s.substr(pos+1);
64            // cout << "e at : " << pos << ", " << s_before_e << " " << s_after_e << endl;
65            if(s_before_e.empty() || s_after_e.empty()) return false;
66        }else{
67            // e_count == 0
68            s_before_e = s;
69            // cout << "s: " << s << endl;
70        }
71        
72        //process and remove '+' and '-'
73        if(!s_before_e.empty() && !isPosNegCorrect(s_before_e)) return false;
74        if(!s_after_e.empty() && !isPosNegCorrect(s_after_e)) return false;
75        
76        // cout << "after removing + and -: " << s_before_e << " " << s_after_e << endl;
77        
78        //"." is invalid
79        if(s_before_e == ".") return false;
80        
81        //"0.1", 0." and ".1" are valid
82        if(count(s_before_e.begin(), s_before_e.end(), '.') > 1){
83            return false;
84        }
85        if(!s_after_e.empty() && count(s_after_e.begin(), s_after_e.end(), '.') > 0){
86            return false;
87        }
88        
89        return true;
90    }
91};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.