LeetCode 065 Valid Number

题目描述

Validate if a given string is numeric.

Some examples:

"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

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.

代码

public class Solution {

    public boolean isNumber(String s) {

        if (s == null || s.length() == 0) {
            return false;
        }

        char[] chars = s.toCharArray();
        int start = 0, end = chars.length - 1;

        // 除去前后的空格
        while ((start < end) && chars[start] == ' ') {
            start++;
        }
        while ((start < end) && chars[end] == ' ') {
            end--;
        }

        // 因为while的循环条件是start < end,s为空格时,会剩下一个空格
        if (chars[start] == ' ') {
            return false;
        }

        boolean dot = false;
        boolean num = false;
        boolean ex = false;

        for (int i = start; i <= end; i++) {

            char c = chars[i];

            if (c >= '0' && c <= '9') {
                num = true;
            } else if (c == 'e') {
                if (ex)
                    return false;
                if (!num)
                    return false;

                ex = true;
                num = false;
                dot = false;
            } else if (c == '.') {
                if (dot) {
                    return false;
                }
                if (ex) {
                    return false;
                }
                dot = true;
            } else if (c == '+' || c == '-') {
                if (num || dot) {
                    return false;
                }
            } else {
                return false;
            }
        }

        return num;
    }
}

参考链接

Valid Number-GitHub

    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/48876651
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞