日期:2026年7月30日
LeetCode 題目連結:3014. Minimum Number of Pushes to Type Word I
解題想法
簡單題。題目給一個字串 $word$,仿照用電話按鈕輸入字母的方式,但可以重新分配數字按鈕對應的字母,要計算輸入入 $word$ 至少要按幾下。共有 8 個按鈕可以對應到字母,如果 $word$ 的長度 $n \leq 8$,可以將 $n$ 個字母分配給不同的按鈕,各按 1 下即可;如果 $n > 8$,先處理 8 個字母,$n$ 更新為 $n-8$,下一步最多處理 8 個字母,各按 2 下即可輸入;重複以上的過程直到沒有字母需要輸入為止。
Python 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 19.18 MB, beats 83.33%.
class Solution:
def minimumPushes(self, word: str) -> int:
n = len(word) # 字串長度
ans, cof = 0, 1 # 答案,要按幾下才能輸入一個字母
while n > 0:
if n > 8: # 剩下超過 8 個字母
ans += 8 * cof # 答案加上 8 * cof
cof += 1 # cof 加 1
n -= 8 # 字母數量減 8
else: # 剩下不到 8 個字母
ans += n * cof # 答案加上 n * cof
n = 0 # 歸零
return ans
C++ 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 8.26 MB, beats 77.73%.
class Solution {
public:
int minimumPushes(string word) {
// 字串長度,答案,要按幾下才能輸入一個字母
int n = (int)word.size(), ans = 0, cof = 1;
while(n > 0) {
if (n > 8) { // 剩下超過 8 個字母
ans += 8 * cof; // 答案加上 8 * cof
cof++; // cof 加 1
n -= 8; // 字母數量減 8
} else { // 剩下不到 8 個字母
ans += n * cof; // 答案加上 n * cof
n = 0; // 歸零
}
}
return ans;
}
};
C 語言程式碼
Runtime: 0 ms, beats 100.00%. Memory: 8.69 MB, beats 88.24%.
int minimumPushes(char* word) {
// 字串長度,答案,要按幾下才能輸入一個字母
int n = strlen(word), ans = 0, cof = 1;
while(n > 0) {
if (n > 8) { // 剩下超過 8 個字母
ans += 8 * cof; // 答案加上 8 * cof
cof++; // cof 加 1
n -= 8; // 字母數量減 8
} else { // 剩下不到 8 個字母
ans += n * cof; // 答案加上 n * cof
n = 0; // 歸零
}
}
return ans;
}
沒有留言:
張貼留言