문장과 스크린 사이즈가 주어진다. 해당 문장을 스크린에 몇번 담을 수 있는지 파악하라.
Input: sentence = ["a", "bcd", "e"], rows = 3, cols = 6
Output: 2
Explanation:
a-bcd-
e-a---
bcd-e-
The character '-' signifies an empty space on the screen.
discussion을 참고했다. 배열 인덱싱이 많고, 코드 복잡도가 높아서 어려운 문제였다.
아이디어
unordered_map 배운것
class Solution {
public:
int wordsTyping(vector<string>& sentence, int rows, int cols) {
unordered_map<int, int> table;
// key: idx of sentence
// value: how many word in a line
int idx = 0;
int ssize = sentence.size();
int num = 0;
for (int i = 0; i < rows; i++) {
idx = num % ssize;
if (table.count(idx) == 0) {
// if new, calculate number of words in a line from begin with sentence[idx]
int cnt = 0, len = 0;
int j = idx;
while (len < cols) {
j = (j + 1) % ssize;
if (len + sentence[j].size() > cols)
break;
len += sentence[j].size() + 1;
cnt++;
}
num += cnt;
table[idx] = cnt;
} else {
// if exist, just return from hashtable
num += table[idx];
}
}
return num / ssize;
}
};
brute force 방법. 아래 예제에서 TLE발생. (34 / 51 test cases passed)
["a","b"]
20000
20000
class Solution {
public:
int wordsTyping(vector<string>& sentence, int rows, int cols) {
int tot_screen = 0;
int idx = 0;
int nr_sent = sentence.size();
int remein_col = cols;
int cur_row = 0;
int cur_s_len = 0;
int *len_arr = new int[nr_sent];
for (int i = 0; i < nr_sent; i++)
len_arr[i] = sentence[i].size();
while (cur_row < rows) {
cur_s_len = len_arr[idx];
if (cur_s_len <= remein_col) { /* fit in cur row */
if (cur_s_len == remein_col)
remein_col -= cur_s_len;
else
remein_col -= (cur_s_len + 1);
idx++;
if (idx >= nr_sent) {
idx = 0;
tot_screen++;
}
} else { /* doesn't fit in cur row */
remein_col = cols;
cur_row++;
}
}
return tot_screen;
}
};