找出字符串中第一个只出现一次的字符(day20)

题目描述:

链接:牛客

找出字符串中第一个只出现一次的字符.

输入描述:

输入几个非空字符串

输出描述:

 输出第一个只出现一次的字符,如果不存在输出-1

示例:
输入

asdfasdfo
aabb

输出

o
-1

解题思路:

1.将输入字符串转化为字符数组并将每个元素存入HashMap中;

2.拿到数组中的每个元素在HashMap中对应的value值,若value==1则输出该字符并改变flag == true(避免退出循环后继续打印-1),break结束循环,循环结束后若flag ==true,则说明该字符串中没有单独的字符串则打印-1;

代码如下:

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.nextLine();
            
            char[] ch = str.toCharArray();
            HashMap<Character,Integer> map = new HashMap<>();
            for(char x : ch){
                map.put(x,map.getOrDefault(x,0)+1);
            }
            boolean flag = true;
            for(char x : ch){
                if(map.get(x) == 1){
                    System.out.println(x);
                    flag = false;
                    break;
                }
            }
            if(flag){
                System.out.println(-1);
            }

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来回答你的问题。 1. 给出一个字符串找出字符串所有的单词。 可以通过正则表达式来实现,代码如下: ```javascript const str = "hello world, I'm a developer"; const words = str.match(/\b\w+\b/g); console.log(words); // ["hello", "world", "I'm", "a", "developer"] ``` 这里使用了 `\b\w+\b` 匹配单词的正则表达式,其 `\b` 表示单词边界,`\w+` 表示匹配一个或多个字母数字下划线字符。 2. 从键盘输入两个字符串,在第一个字符串删除第二个字符串字符。 可以先将第二个字符串转换为字符数组,然后遍历该数组,在第一个字符串删除对应的字符。代码如下: ```javascript const str1 = "hello world"; const str2 = "o"; const chars = str2.split(""); for (let i = 0; i < chars.length; i++) { const char = chars[i]; str1 = str1.replace(new RegExp(char, "g"), ""); } console.log(str1); // "hell wrld" ``` 这里使用了 `split` 将第二个字符串转换为字符数组,然后遍历该数组,使用 `replace` 在第一个字符串删除对应的字符。 3. 使用正则表达式匹配日期格式,如 2022年11月30日。 可以使用如下正则表达式匹配日期格式: ```javascript const str = "2022年11月30日"; const dateRegex = /(\d{4})年(\d{1,2})月(\d{1,2})日/; const match = str.match(dateRegex); const year = match[1]; const month = match[2]; const day = match[3]; console.log(`${year}-${month}-${day}`); // "2022-11-30" ``` 这里使用了 `(\d{4})年(\d{1,2})月(\d{1,2})日` 匹配日期格式的正则表达式,其 `(\d{4})` 表示匹配 4 个数字的年份,`(\d{1,2})` 表示匹配 1 到 2 个数字的月份和日期。然后使用 `match` 方法匹配字符串,获取到匹配的年份、月份和日期,并使用模板字符串拼接成标准日期格式输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值