【算法入门】AppearOnce 只出现过一次的字母 JAVA实现

收到了一个来自黄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的时候就遇到过差不多的题,思路还是非常清晰的。

  1. 设置数组大小为26的 b[26] 表示26个字母。
  2. 遍历目标字符串的每一个字符,减去’a’,得到的值对应数组下标的数组元素加一,这样就能保存每一个字母出现的次数。
  3. 最后将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 的数据结构我的基本功还是太差了,最近有在恶补,也在顺便刷题,还有十多道力扣没写题解,后面会慢慢补上。下次准备写一篇动态规划的专题,应该明天或者后天能写好!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值