zoukankan      html  css  js  c++  java
  • LeetCode 65. Valid Number

    原题链接在这里:https://leetcode.com/problems/valid-number/

    题目:

    Validate if a given string can be interpreted as a decimal number.

    Some examples:
    "0" => true
    " 0.1 " => true
    "abc" => false
    "1 a" => false
    "2e10" => true
    " -90e3   " => true
    " 1e" => false
    "e3" => false
    " 6e-1" => true
    " 99e2.5 " => false
    "53.5e93" => true
    " --6 " => false
    "-+3" => false
    "95a54e53" => false

    Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:

    • Numbers 0-9
    • Exponent - "e"
    • Positive/negative sign - "+"/"-"
    • Decimal point - "."

    Of course, the context of these characters also matters in the input.

    Update (2015-02-10):
    The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

    题解:

    用多个flag来检测. 原string trim后从e拆开,前面部分可以有dot, 后面部分不可以有dot. 

    Note: dot后面可能没有数字. After e, there must be digit.

    Time Complexity: O(s.length()).

    Space: O(1).

    AC Java:

     1 class Solution {
     2     public boolean isNumber(String s) {
     3         if(s == null || s.length() == 0){
     4             return false;
     5         }
     6         
     7         s = s.trim();
     8         
     9         boolean eSeen = false;
    10         boolean dotSeen = false;
    11         boolean digitSeen = false;
    12         
    13         for(int i = 0; i<s.length(); i++){
    14             char c = s.charAt(i);
    15             if(c == '+' || c == '-'){
    16                 if(i != 0 && s.charAt(i-1) != 'e'){
    17                     return false;
    18                 }
    19             }else if(Character.isDigit(c)){
    20                 digitSeen = true;
    21             }else if(c == '.'){
    22                 if(dotSeen || eSeen){
    23                     return false;
    24                 }
    25                 
    26                 dotSeen = true;
    27             }else if(c == 'e'){
    28                 if(eSeen || !digitSeen){
    29                     return false;
    30                 }
    31                 
    32                 eSeen = true;
    33                 digitSeen = false;
    34             }else{
    35                 return false;
    36             }
    37         }
    38         
    39         return digitSeen;
    40     }
    41 }
  • 相关阅读:
    效果超酷的textarea的输入字数限提示
    【设计模式(七)】结构型模式之桥接模式
    【设计模式(六)】适配器模式
    【设计模式(四)】原型模式
    【设计模式(三)】工厂模式
    【设计模式(二)】单例模式
    【设计模式(一)】设计模式概览与六大设计原则
    【算法刷题】无重复字符的最长子串
    【算法刷题】全排列 II
    【算法刷题】LRU缓存模拟
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4951768.html
Copyright © 2011-2022 走看看