請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù)用來(lái)判斷字符串是否表示數(shù)值(包括整數(shù)和小數(shù))。例如院促,字符串"+100"筏养、"5e2"、"-123"常拓、"3.1416"渐溶、"-1E-16"、"0123"都表示數(shù)值弄抬,但"12e"茎辐、"1a3.14"、"1.2.3"、"+-5"及"12e+5.4"都不是拖陆。
假設(shè)字符串為A.BeC或A.BEC, 也就是整數(shù)部分為A弛槐,小數(shù)部分為B,指數(shù)部分為C慕蔚,按順序判斷是否包含這三部分丐黄。
- 在字符串后添加結(jié)束標(biāo)志
- 使用全局index遍歷字符串
- scanInteger掃描有符號(hào)整數(shù),用來(lái)匹配A和C部分
- scanUnsignedInteger掃描無(wú)符號(hào)整數(shù)孔飒,用來(lái)匹配B部分
class Solution {
var index = 0
func isNumber(_ s: String) -> Bool {
guard s.count != 0 else {
return false
}
// 將字符串轉(zhuǎn)為字符數(shù)組
let sArray = Array(s)
// 排除空格
while index < sArray.count && sArray[index] == " " {
index += 1
}
// 驗(yàn)證整數(shù)部分
var numeric = scanInteger(sArray)
if index < sArray.count && sArray[index] == "." {
index += 1
// 驗(yàn)證小數(shù)部分
numeric = scanUnsignInteger(sArray) || numeric
}
// 如果含e指數(shù)灌闺,則需驗(yàn)證指數(shù)
if index < sArray.count && (sArray[index] == "e" || sArray[index] == "E"){
index += 1
numeric = numeric && scanInteger(sArray)
}
while index < sArray.count && sArray[index] == " "{
index += 1
}
return numeric && (index == sArray.count)
}
func scanInteger(_ sArray: Array<Character>) -> Bool {
if index < sArray.count && (sArray[index] == "+" || sArray[index] == "-") {
index += 1
}
return scanUnsignInteger(sArray)
}
func scanUnsignInteger(_ sArray: Array<Character>) -> Bool{
let before = index
while index < sArray.count && sArray[index] >= "0" && sArray[index] <= "9" {
index += 1
}
return index > before
}
}