애플이 문제~
단순하게 푸는 것도 괜찮다는 것을 느낌
Given an array words of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
arr = list(words[0])
for i in range(1, len(words)):
tmp = list(words[i])
for j in range(len(arr)):
if arr[j] not in tmp:
arr[j] = "0"
else:
tmp[tmp.index(arr[j])] = "1"
answer = []
for i in range(len(arr)):
if arr[i] != "0":
answer.append(arr[i])
return answer
words[0]
을 기준으로 words[i]
에 words[0]
문자들이 있는지 확인
있으면 words[0]
문자 값은 0 으로, words[i]
문자 값은 1 로 바꿔주고
마지막에 0 이 아닌 값들만 answer
에 넣어줌
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
result = []
for i in range(len(A[0])):
result.append(A[0][i])
for j in range(1, len(A)):
if A[0][i] not in A[j]:
result.pop()
break
else:
# 한번 찾은 부분은 또 사용하면 안되니까 없애줌
tmp = A[j].index(A[0][i])
A[j] = A[j][:tmp] + A[j][tmp+1:]
return result
A[0]
을 기준으로 각 문자들이 모든 문자열에 있는지 확인
한번 찾은 부분은 또 사용하면 안되니까 잘라내줌
저번에 푼 방식인데 훨씬 나은듯
Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s, split it in the maximum amount of balanced strings.
Return the maximum amount of split balanced strings.
class Solution:
def balancedStringSplit(self, s: str) -> int:
stack = ""
cnt = 0
for i in range(len(s)):
stack += s[i]
if len(stack) != 0:
tmp = collections.Counter(stack)
if tmp["L"] == tmp["R"]:
cnt += 1
return cnt
stack
변수에 L
, R
넣어주고 개수가 같으면 cnt += 1
class Solution:
def balancedStringSplit(self, s: str) -> int:
left = 0
right = 0
result = 0
for i in range(len(s)):
if s[i] == "L":
left += 1
if s[i] == "R":
right += 1
if left == right:
result += 1
return result
L
, R
개수 세줘서 같을때마다 result + 1
이건 저번에 풀었던 건데 훨씬 나은듯2