1、计算器
给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。
表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
示例1:
输入: "3+2*2"
输出: 7
示例2:
输入: " 3/2 "
输出: 1
方法比较笨拙,字符串先转数组,先循环得到一个拆分的数组,然后再循环计算乘除法,再循环计算加减,
/**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
let symbolArr = []
let numArr = s.replace(/\s/g, '').split('')
let symbolS = '+-*/'
let dealArr = []
let countArr = []
let type = 0 // 0表示未存值,1表示数字,2表示*或者/,3表示+/-
for (let i = 0; i < numArr.length; i++) {
if (symbolS.indexOf(numArr[i]) === -1) {
if (i === 0) {
dealArr.push(numArr[i])
} else {
if (dealArr.length > 0 && symbolS.indexOf(dealArr[dealArr.length - 1]) === -1) {
dealArr[dealArr.length - 1] = parseInt(dealArr[dealArr.length - 1]) * 10 + parseInt(numArr[i])
} else {
dealArr.push(numArr[i])
}
}
} else {
dealArr.push(numArr[i])
}
}
for(let i = 0; i < dealArr.length; i++) {
if (symbolS.indexOf(dealArr[i]) === -1) {
if (i === 0) {
countArr.push(dealArr[i])
} else {
if (type === 0) {
countArr.push(dealArr[i])
} else if (type === 1) {
countArr[countArr.length - 1] = Number(countArr[countArr.length - 1] * 10) + Number(dealArr[i])
} else if (type === 3) {
countArr.push(dealArr[i])
} else if (type === 2) {
if (countArr[countArr.length - 1] === '*') {
countArr[countArr.length - 2] = Number(countArr[countArr.length - 2]) * Number(dealArr[i])
} else {
countArr[countArr.length - 2] = Math.floor(countArr[countArr.length - 2] / dealArr[i])
}
countArr.pop()
}
}
type = 1
} else if (dealArr[i] === '+' || dealArr[i] === '-') {
type = 3
countArr.push(dealArr[i])
} else if (dealArr[i] === '*' || dealArr[i] === '/') {
type = 2
countArr.push(dealArr[i])
}
}
console.log(countArr, 'countArr')
let finalCount = 0
for (let i = 0; i < countArr.length; i++) {
if (countArr.length === 1) {
finalCount = countArr[i]
} else {
if (i + 1 < countArr.length) {
if (countArr[i] === '+') {
finalCount = finalCount + Number(countArr[i+1])
i++
} else if (countArr[i] === '-') {
console.log(finalCount, Number(countArr[i+1]), '333')
finalCount = finalCount - Number(countArr[i+1])
i++
} else {
finalCount = Number(countArr[i])
}
console.log(finalCount, '111111')
}
}
}
return finalCount
};
2、重新排列字符串
给你一个字符串 s 和一个 长度相同 的整数数组 indices 。
请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。
返回重新排列后的字符串。
示例:
输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
输出:"leetcode"
解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。
/**
* @param {string} s
* @param {number[]} indices
* @return {string}
*/
var restoreString = function(s, indices) {
let letterArr = s.split('')
let arr = new Array()
for (let i = 0; i < indices.length; i++) {
arr[indices[i]] = letterArr[i]
}
return arr.join('')
};