You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.
Return the number of strings in words that are a prefix of s.
A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.
한글 요약 :
s의 접두어가 될 수 있는 갯수를 구하는 문제입니다.
Example 1
Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
Output: 3
Example 2
Input: words = ["a","a"], s = "aa"
Output: 2
제한사항
- 1 ≤ words.length ≤ 1000
- 1 ≤ words[i].length, s.length ≤ 10
- words[i] and s consist of lowercase English letters only.
class Solution:
def countPrefixes(self, words: List[str], s: str) -> int:
answer = 0
for word in words:
check = True
if len(word) > len(s) : continue
for i in range(len(word)):
if word[i] != s[i]:
check = False
break;
if check : answer += 1
return answer
class Solution:
def countPrefixes(self, words: List[str], s: str) -> int:
return sum([s.startswith(word) for word in words])
... 멋지다..
startswith는 문자열이 특정 문자로 시작하는 지를 True, False로 알려줍니다.
두번째 인자를 넣으면 두번째 인자의 값부터 검색합니다.
s = "abcdefg"
s.startswith('a') # True
s.startswith('e') # False
s.startswith('e', 4) #True
startswith의 반대도 있습니다.
두번째 인자로 시작 인덱스, 세번째 인자로 끝나는 인덱스를 지정할 수 도 있습니다.
s = "abcdefg"
s.endswith('a') # False
s.endswith('g') # True
s.endswith('e', 0, 5) #True 세번째 인자는 5번인덱스 전까지라는 뜻이다.