【Lintcode】1485. Holy Grail spell

記錄演算法發表於2020-12-11

題目地址:

https://www.lintcode.com/problem/holy-grail-spell/description

給定一個只含英文字母的長 n n n的字串,返回大小寫都出現在其中的字典序最大的字母的大寫。題目保證解存在。

程式碼如下:

public class Solution {
    /**
     * @param Spell: The Spell
     * @return: nothing
     */
    public char holyGrailspell(String Spell) {
        // Write your code here
        boolean[] exista = new boolean[26], existA = new boolean[26];
        for (int i = 0; i < Spell.length(); i++) {
            char ch = Spell.charAt(i);
            if ('a' <= ch && ch <= 'z') {
                exista[ch - 'a'] = true;
            } else {
                existA[ch - 'A'] = true;
            }
        }
    
        for (int i = 25; i >= 0; i--) {
            if (exista[i] && existA[i]) {
                return (char) ('A' + i);
            }
        }
        
        return 0;
    }
}

時間複雜度 O ( n ) O(n) O(n),空間 O ( 1 ) O(1) O(1)