[파이썬][Leetcode][릿코드] Final Value of Variable After Performing Operations
1. 문제
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. 해결방법 시간복잡도
- 단순 코딩 O(N)
- 더 쉽게 O(1)
3. 문제 해결 및 코드
-
주석을 참고하면서 이해를 돕습니다.
4. 알고리즘 및 해설
- 해당 문제에서 제시한 특정 문자에 대한 답으로 딕셔너리를 만든다.
- 이후 해당 값이 키값에 존재한다면 해당 키에 값을 추가한다.
- 이후 해당 키값들의 합을 출력한다.
5. 더 쉽게 알아보기
- 그냥 count()로 쉽게 해결이 가능했다.
class Solution: def finalValueAfterOperations(self, operations: List[str]) -> int: return operations.count("X++") + operations.count("++X") - operations.count("X--") - operations.count("--X")