實現10之內四則運算(只包含數字,+-*/和小括號)算法
/** * 把Character轉換成Doublec * @param {Character} c - 須要轉換的字符 * @return {Double} 返回c對應的數字 */
func _c2n(_ c: Character) throws -> Double{
guard case "0" ... "9" = c else {
throw AlgorithmError.msg("符號範圍錯誤");
}
let zero = "0".unicodeScalars.first!.value;
return Double(c.unicodeScalars.first!.value - zero);
}
/** * 最小單元計算 {n1}{mark}{n2} * @param {Double} n1 - 數字1 * @param {Double} n2 - 數字2 * @param {Character} mark - 符號 * @return {Double} 返回 {n1}{mark}{n2} 的結果 */
func _eval(_ n1: Double, _ n2: Double, _ mark: Character) throws -> Double{
switch mark {
case "+":
return n1 + n2;
case "-":
return n1 - n2;
case "*":
return n1 * n2;
case "/":
if n2 == 0 {
throw AlgorithmError.msg("除0錯誤");
}
return n1 / n2;
default:
throw AlgorithmError.msg("符號錯誤");
}
}
/** * 比較符號 * @param {String} a - 符號a * @param {String} b - 符號b * @return {Bool} 若是a的優先級<=b的優先級返回true,不然返回false */
func _arithmeticCompare(_ a: Character, _ b: Character) throws -> Bool {
switch b {
case "+", "-":
return a == "+" || a == "-";
case "*", "/":
return true;
case "(":
return false;
default:
throw AlgorithmError.msg("非法符號");
}
}
/** * 計算10之內的四則運算 * @param {String} str - 輸入中綴表達式 * @return {Double} - 返回計算結果 */
func arithmetic(_ str: String) throws -> Double{
//結果棧
let retStack = Stack<Character>();
//符號棧
let markStack = Stack<Character>();
var lastC: Character? = nil;
for c in str{
switch c{
case "(":
if let lc = lastC, case "0"..."9" = lc{
throw AlgorithmError.msg("發現錯誤");
}
//直接進符號
markStack.push(c);
break
case ")":
//依次出棧直到括號結束
while markStack.top() != "(" && markStack.count() > 0 {
if let m = markStack.pop(){
retStack.push(m);
}
}
if markStack.count() > 0 {
markStack.pop();
}else{
throw AlgorithmError.msg("發現錯誤");
}
break
case "+", "-", "*", "/":
//比c優先級高的都進結果棧
if let t = markStack.top(){
while true {
if let c = try? _arithmeticCompare(c, t), c{
markStack.pop();
retStack.push(t);
if markStack.count() == 0{
break;
}
}else{
break;
}
}
}
markStack.push(c);
break;
case "0"..."9":
if let lc = lastC , case "0"..."9" = lc {
throw AlgorithmError.msg("發現錯誤");
}
//直接進結果
retStack.push(c);
break;
default:
throw AlgorithmError.msg("發現錯誤");
}
lastC = c;
}
//符號棧可能不空
while markStack.count() > 0 {
retStack.push(markStack.pop()!);
}
//計算結果
let numStack = Stack<Double>();
while retStack.count() > 0 {
if let c = retStack.shift(){
if case "0"..."9" = c {//數字
numStack.push(try _c2n(c));
}else{//符號
if numStack.count() >= 2{
if let n1 = numStack.pop(), let n2 = numStack.pop() {
numStack.push(try _eval(n2, n1, c));
}
}else{
throw AlgorithmError.msg("發現錯誤");
}
}
}
}
if numStack.count() != 1{
throw AlgorithmError.msg("發現錯誤");
}
return numStack.pop()!;
}
複製代碼
function size(inputArr){
let stack1 = [];
let stack2 = [];
let validMark = (m) => {
return ['+', '-', '*', '/', '(', ')'].includes(m);
}
let compareDict = {
'+': 0,
'-': 0,
'*': 1,
'/': 1
}
let compare = (a, b) => {
if(!compareDict.hasOwnProperty(a) || !compareDict.hasOwnProperty(b)){
throw `錯誤符號 a=${a} b=${b}`;
}
return compareDict[a] < compareDict[b];
}
//中綴轉後綴
//數字直接入棧2,符號若是優先級低於棧頂,依次出棧1,入棧2.
for (const e of inputArr) {
let num = Number.parseInt(e);
//數字直接入棧2
if(!Number.isNaN(num)){
stack2.push(num);
}else{//非數字,2種狀況,多是括號,多是非括號
if(!validMark(e)){
throw `非法符號${e}`;
}
if(e == '('){//左括號直接入棧1
stack1.push(e);
}else if(e == ')'){//右括號依次出棧
let mark = null;
let valid = false;
while(stack1.length > 0 && mark != '('){//複雜度O(1)
mark = stack1.pop();
if(mark != '('){
stack2.push(mark);
}else{
valid = true;
}
}
if(!valid){
throw '非法表達式';
}
}else{//若是是正常運算符,則依次與棧1頂元素比較,若棧頂元素優先級高,則出棧
let mark = null;
let handled = false;
while(stack1.length > 0 && mark != '('){//複雜度O(1)
mark = stack1.pop();
//只有棧頂元素優先級 < e時才結束循環,不然棧頂元素優先級 >= e時,就不停出棧
if(mark == '(' || compare(mark, e)){
stack1.push(mark);
stack1.push(e);
handled = true;
break;
}else{
stack2.push(mark);
}
}
//全部符號都出棧了或者遇到了'('
if(!handled){
stack1.push(e);
}
}
}
}
while(stack1.length > 0){
stack2.push(stack1.pop());
}
if(stack1.length != 0){
throw '表達式錯誤';
}
while(stack2.length > 0){//O(n)
let mark = stack2.shift();
let num = Number.parseInt(mark);
if(!Number.isNaN(num)){//數字
stack1.push(num);
}else{//符號
let n1 = stack1.pop();
let n2 = stack1.pop();
if(!n1 || !n2){
throw '表達式錯誤';
}
let v = eval(`${n2}${mark}${n1}`);
stack1.push(v);
}
}
console.log(`stack1=${stack1}`);
return stack1.pop();
}
複製代碼
上述2個過程複雜度都比較低,若是遇到數字都是直接保存,遇到符號會進行一次比較或計算,時間複雜度爲O(n)。 上述算法中使用了3個棧或隊列,其中2個棧可以重複使用,空間複雜度爲O(2n)。swift
上面的算法只是關注算法自己邏輯,健壯性及通用性比較差,若是用於正式的程序,還須要增長不少驗證邏輯及更多運算符的支持。ui