收到了一个来自黄sir的java作业题,最近也在用java做力扣,赶紧拿来练练手!
题目描述:
// Complete the method appearOnce that on input a non-empty string, // prints the first character that appears exactly once in the string. // You may assume that the input string will contain at least one such character. // You must use String methods in lecture notes. // You must NOT use StringBuilder or Regular Expression methods.
这段大概意思就说apearOnce方法要找出传入的string中第一个只出现过一次的字符并且返回。题目也贴心地给出了几个示例~
String input = "abcdbaddab";
System.out.println(appearOnce(input)); // 'c'
input = "abcdcb";
System.out.println(appearOnce(input)); // 'a'
input = "x";
System.out.println(appearOnce(input)); // 'x'
好了题目的意思非常清晰了!
解题思路
以前刚学c的时候就遇到过差不多的题,思路还是非常清晰的。
- 设置数组大小为26的 b[26] 表示26个字母。
- 遍历目标字符串的每一个字符,减去’a’,得到的值对应数组下标的数组元素加一,这样就能保存每一个字母出现的次数。
- 最后将b中第一个为1的字符返回就大功告成了!
代码
public class AppearOnce {
public static char appearOnce(String input) {
char[] chs=input.toCharArray();//将字符串转换为字符数组
int[] b = new int[26];
for(int i = 0; i<chs.length; i++) {
b[chs[i]-'a']++;//遍历每一个字符,对应数组元素+1
}
for(int i = 0; i<chs.length; i++) {
if (b[chs[i] - 'a'] == 1)
{
return chs[i];
}
}
return 'o';
}
public static void main(String[] args) {
String input = "abcdbaddab";
System.out.println(appearOnce(input)); // 'c'
input = "abcdcb";
System.out.println(appearOnce(input)); // 'a'
input = "x";
System.out.println(appearOnce(input)); // 'x'
}
}
结语
这个题的关健就是利用char和int的直接转换,写的还是多少有点不够优雅哈哈哈!我感觉是肯定可以优雅地用哈希树来解决的,但是又有点杀鸡用牛刀的意思哈哈,不过 java 的数据结构我的基本功还是太差了,最近有在恶补,也在顺便刷题,还有十多道力扣没写题解,后面会慢慢补上。下次准备写一篇动态规划的专题,应该明天或者后天能写好!