摘要:两种情况有无,如上所示。如何判断是否只有一个之后的长度小于等于。注意,为空只有在字符串最末位或者只有都是错误的。规则若字符串首位为,取其,然后将应用转换为数组,逐位判断字符,出现将置如已经置,再次出现则直接返回。
Problem
Validate if a given string is numeric.
Example"0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => trueNote
if !e A can be "+/-" + int + "." + int if e: AeB A can be "+/-" + int + "." + int B can be "+/-" + int
两种情况:有无e,如上所示。
然后按有无e来拆分字符串,若拆分之后只有一部分,即用helper()函数判断是否满足构成数的规则;若有两部分,则对前一部分按数A(可以有小数部分)分析,后一部分按构成数B分析(只能为整数)。
如何判断是否只有一个e?split()之后的String[]长度小于等于2。
由于数A和数B的区别只存在于有没有小数点".",建立一个flag hasDot(),其他应用一样的规则即可。注意,s为空、只有"e"、"e"在字符串最末位、或者只有"."都是错误的。
规则:若字符串首位为+/-,取其.substring(1),然后将string应用toCharArray()转换为char数组,逐位判断字符,出现"."将hasDot()置true;如hasDot()已经置true,再次出现"."则直接返回false。然后判断其余位是否为数字即可。
Solutionpublic class Solution {
public boolean isNumber(String s) { s = s.trim(); if (s == null || (s.length() > 0 && s.charAt(s.length()-1) == "e") || s.equals(".")) return false; String[] strs = s.split("e"); if (strs.length > 2) return false; boolean res = helper(strs[0], false); if (strs.length == 2) { res = res && helper(strs[1], true); } return res; } public boolean helper(String s, boolean hasDot) { if (s.length() > 0 && (s.charAt(0) == "+" || s.charAt(0) == "-")) s = s.substring(1); char[] ch = s.toCharArray(); if (ch.length == 0) return false; for (int i = 0; i < ch.length; i++) { if (ch[i] == ".") { if (hasDot) return false; hasDot = true; } else if (!(ch[i] >= "0" && ch[i] <= "9")) return false; } return true; }
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65520.html
Problem Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0s and 1s, and all the 0s and all the 1s in these substrings are grouped consecutively. Subs...
Problem Youre now a baseball game point recorder. Given a list of strings, each string can be one of the 4 following types: Integer (one rounds score): Directly represents the number of points you get...
Problem A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For 1-byte character, the first bit is a 0, followed by its unicode code.For n-bytes character, the first n...
Valid Palindrome Problem Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example A man, a plan, a canal: Panama is a palindrome. race a ca...
LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...
阅读 3526·2021-08-31 09:39
阅读 1797·2019-08-30 13:14
阅读 2874·2019-08-30 13:02
阅读 2750·2019-08-29 13:22
阅读 2277·2019-08-26 13:54
阅读 742·2019-08-26 13:45
阅读 1567·2019-08-26 11:00
阅读 946·2019-08-26 10:58