自己写的,用hash
class Solution {
public:
string greatestLetter(string s) {
int upper[26] = {0};
int lower[26] = {0};
string ans;
for (auto ch : s){
if (isupper(ch)){
upper[ch-'A'] = 1;
} else if (islower(ch)){
lower[ch-'a'] = 1;
}
}
for (int i = 25; i >= 0; i--) {
if (lower[i] && upper[i]) {
char best = char(i+'A');
ans += best;
break;
}
}
return ans;
}
};
看答案,可以用bitmap
class Solution {
public:
string greatestLetter(string s) {
int lower = 0, upper = 0;
for (auto c : s) {
if (islower(c)) {
lower |= 1 << (c - 'a');
} else {
upper |= 1 << (c - 'A');
}
}
for (int i = 25; i >= 0; i--) {
if (lower & upper & (1 << i)) {
return string(1, 'A' + i);
}
}
return "";
}
};