摘要:兩種情況有無,如上所示。如何判斷是否只有一個之后的長度小于等于。注意,為空只有在字符串最末位或者只有都是錯誤的。規則若字符串首位為,取其,然后將應用轉換為數組,逐位判斷字符,出現將置如已經置,再次出現則直接返回。
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; }
}
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 3548·2021-08-31 09:39
閱讀 1854·2019-08-30 13:14
閱讀 2918·2019-08-30 13:02
閱讀 2769·2019-08-29 13:22
閱讀 2341·2019-08-26 13:54
閱讀 767·2019-08-26 13:45
閱讀 1586·2019-08-26 11:00
閱讀 982·2019-08-26 10:58