[파이썬][Leetcode][릿코드] Final Value of Variable After Performing Operations
1. 문제Permalink
2011. Final Value of Variable After Performing Operations
Easy
There is a programming language with only four operations and one variable X
:
++X
andX++
increments the value of the variableX
by1
.--X
andX--
decrements the value of the variableX
by1
.
Initially, the value of X
is 0
.
Given an array of strings operations
containing a list of operations, return the final value of X
after performing all the operations.
Example 1:
Input: operations = ["--X","X++","X++"] Output: 1 Explanation: The operations are performed as follows: Initially, X = 0. --X: X is decremented by 1, X = 0 - 1 = -1. X++: X is incremented by 1, X = -1 + 1 = 0. X++: X is incremented by 1, X = 0 + 1 = 1.
Example 2:
Input: operations = ["++X","++X","X++"] Output: 3 Explanation: The operations are performed as follows: Initially, X = 0. ++X: X is incremented by 1, X = 0 + 1 = 1. ++X: X is incremented by 1, X = 1 + 1 = 2. X++: X is incremented by 1, X = 2 + 1 = 3.
Example 3:
Input: operations = ["X++","++X","--X","X--"] Output: 0 Explanation: The operations are performed as follows: Initially, X = 0. X++: X is incremented by 1, X = 0 + 1 = 1. ++X: X is incremented by 1, X = 1 + 1 = 2. --X: X is decremented by 1, X = 2 - 1 = 1. X--: X is decremented by 1, X = 1 - 1 = 0.
Constraints:
1 <= operations.length <= 100
operations[i]
will be either"++X"
,"X++"
,"--X"
, or"X--"
.
출처: Leetcode, https://leetcode.com/
2. 해결방법 시간복잡도Permalink
- 단순 코딩 O(N)
- 더 쉽게 O(1)
3. 문제 해결 및 코드Permalink
class Solution: | |
def isValid(self, s: str) -> bool: | |
stack = [] # 스택으로 해결 | |
tmp = {")":"(", | |
"]":"[", | |
"}":"{"} | |
# 괄호 열고 닫고 정보 저장 | |
for i in s: | |
if i in tmp.values(): # 만약 괄호가 열리는 경우 | |
stack.append(i) | |
else: | |
if stack and tmp[i] == stack[-1]: | |
# 현재 스택이 존재하고 쌓여있으면서 괄호가 닫히는 경우 | |
stack.pop() | |
else: | |
# 닫을 괄호가 스택에 없거나 열린 괄호랑 다를 경우 | |
return False | |
if stack: return False | |
else: return True |
-
주석을 참고하면서 이해를 돕습니다.Permalink
4. 알고리즘 및 해설Permalink
- 해당 문제에서 제시한 특정 문자에 대한 답으로 딕셔너리를 만든다.
- 이후 해당 값이 키값에 존재한다면 해당 키에 값을 추가한다.
- 이후 해당 키값들의 합을 출력한다.
5. 더 쉽게 알아보기Permalink
- 그냥 count()로 쉽게 해결이 가능했다.
class Solution: def finalValueAfterOperations(self, operations: List[str]) -> int: return operations.count("X++") + operations.count("++X") - operations.count("X--") - operations.count("--X")