【Leetcode_Python & C語言】744. Find Smallest Letter Greater Than Target

題目提供了陣列 letters ,letters 裡的字母都是依 a 到 z排序的。


如果沒有字母大於目標字母,就回傳陣列 letters 中的第一個字母。

Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.

Note that the letters wrap around.

  • For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'.

Example 1:

Input: letters = ["c","f","j"], target = "a"
Output: "c"

Example 2:

Input: letters = ["c","f","j"], target = "c"
Output: "f"

Example 3:

Input: letters = ["c","f","j"], target = "d"
Output: "f"

Example 4:

Input: letters = ["c","f","j"], target = "g"
Output: "j"

Example 5:

Input: letters = ["c","f","j"], target = "j"
Output: "c"


  • 2 <= letters.length <= 104
  • letters[i] is a lowercase English letter.
  • letters is sorted in non-decreasing order.
  • letters contains at least two different characters.
  • target is a lowercase English letter.

Table of Contents

Python 解答:

這題 Leetcode 還蠻直觀的

題目有提及,letter 裡的字母都是依 a 到 z排序的。


class Solution:
    def nextGreatestLetter(self, letters: List[str], target: str) -> str:
        for letter in letters:
            if letter > target:
                return letter
        return letters[0]

C 解答:

C 語言中也是一樣的寫法。

char nextGreatestLetter(char* letters, int lettersSize, char target){
    for (int i=0; i<lettersSize; i++){
        if (letters[i] >target){
            return letters[i];
    return letters[0];

Leave a Comment

Your email address will not be published. Required fields are marked *