You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
func decodeString(_ S:String)->String{letinputChars:[Character]=Array(S)varstackStr:[String]=[]varstackCount:[Int]=[]varcurNum:Int=0varcurStr:String=""
for c in inputChars {
if c.isNumber {
curNum = curNum *10+ Int(String(c))!
continue
}
if c.isLetter {
curStr +=String(c)
continue
}
if c =="["{
stackStr.append(curStr)
stackCount.append(curNum)
curStr =""
curNum =0
continue
}
if c =="]"{varprevStr:String= stackStr.removeLast()letcount= stackCount.removeLast()
for _ in 0..<count {
prevStr += curStr
}
curStr = prevStr
continue
}}returnString(curStr)}
String Calculator
Stack을 만들어서 /, * 가 오면 연산
공간복잡도 O(n)
+, * 만나면 계산해서 저장
공간복잡도 O(1)
func calculate(s:String)->Int{lets:[Character]=Array(s+"+")varstack:[Int]=[]varcurNum:Int=0varprev_op:Character="+"
for c in s {
if c.isNumber {
curNum = curNum*10 + Int(String(c))!
}else if c ==""{
continue
}else{
if prev_op =="+"{
stack.append(curNum)}else if prev_op =="-"{
stack.append(-curNum)}else if prev_op =="*"{stack[stack.count-1]= stack.last! * curNum
}else if prev_op =="/"{stack[stack.count-1]= stack.last! / curNum
}
curNum =0
prev_op = c
}}return stack.reduce(0,+)}print(calculate(s:"7 - 6 / 3 + 3 * 2 + 4"))
// 15
Distance To greater Number
뒤에서 부터 비교한다.
불필요한 정보는 pop한다.
func dailyTemperatures(_ temperatures:[Int])->[Int]{varstack:[(num:Int, index:Int)]=[]varanswer:[Int]=[]
for i in stride(from: temperatures.count-1, through:0, by:-1){letcur=temperatures[i]
while !stack.isEmpty && stack.last!.num < cur {let _ = stack.popLast()}
if stack.isEmpty {
answer.append(0)}else{
answer.append(stack.last!.index - i)}
stack.append((cur, i))}return answer.reversed()}print(dailyTemperatures([39,20,70,36,30,60,80,1]))
// [2, 1, 4, 2, 1, 1, 0, 0]