天津网站建设美丽百度青岛代理公司
题目来源:
leetcode题目,网址:2309. 兼具大小写的最好英文字母 - 力扣(LeetCode)
解题思路:
遍历字符串以获得兼具大小写的英文字母,然后返回最大者或空串即可。
解题代码:
class Solution {public String greatestLetter(String s) {String res="";Set<Character> upper=new HashSet<>();Set<Character> lower=new HashSet<>();for(int i=0;i<s.length();i++){char temp=s.charAt(i);if(Character.isLowerCase(temp)){lower.add(temp);if(upper.contains((char)(temp-'a'+'A'))){if(res.length()==0 || res.charAt(0)-'A'<temp-'a'){res=(char)(temp-'a'+'A')+"";}}}else{upper.add(temp);if(lower.contains((char)(temp-'A'+'a'))){if(res.length()==0 || res.charAt(0)<temp){res=temp+"";}}}}return res;}
}
总结:
官方题解给出了两种解法。第一种时哈希表,他是先使用哈希表保存字符,然后判断倒序遍历 26 个英文字母,返回第一个大小写都出现的字符或空串。第二种是位运算,lower 低26位保存小写字母是否出现,upper 低26位保存大小字母是否出现,然后遍历查找。