[LeetCode] 139. Word Break
Problem
Given a string s
and a dictionary of strings wordDict
, return true
if s
can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
Constraints:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s
andwordDict[i]
consist of only lowercase English letters.- All the strings of
wordDict
are unique.
Solution
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] arr = new boolean[s.length() + 1];
arr[0] = true;
for (int i = 1; i <= s.length(); i++)
for (int j = 0; j < i; j++)
if (arr[j] && wordDict.contains(s.substring(j, i))) {
arr[i] = true;
break;
}
return arr[s.length()];
}
}
Explanation
- 문제를 해결하기 위해선 문자열 s를 자른 부분들이 배열 wordDict에 존재하는지 확인해야 한다.
- for 반복문을 중첩 작성하여 문자열 s의 앞부분부터 자르고, 해당 substring이 배열 wordDict에 존재하는지 확인한다. 변수 i가 나타내는 인덱스가 축이되어 반복을 진행한다.
for (int i = 1; i <= s.length(); i++) for (int j = 0; j < i; j++) if (wordDict.contains(s.substring(j, i)))
- substring(j, i)가 배열 wordDict에 존재하는지 여부를 나타내기 위해 배열 arr을 선언하고 if 조건문의 조건식과 내용을 추가한다.
boolean[] arr = new boolean[s.length() + 1]; arr[0] = true; for (int i = 1; i <= s.length(); i++) for (int j = 0; j < i; j++) if (arr[j] && wordDict.contains(s.substring(j, i))) { arr[i] = true; break; }
- 배열 arr의 마지막 요소가 true면 문자열 s를 배열 wordDict의 요소로 구성할 수 있다는 의미가 되므로 마지막 요소를 반환하도록 한다.
return arr[s.length()];
Leave a comment