找出字符串中第一次出现一次的字符的算法。

链接:https://www.nowcoder.com/questionTerminal/d370c322d06945a5901e8436d1e2e681?orderByHotValue=1&page=1&onlyReference=false
来源:牛客网

用一个记数数组来标记每个字母出现的次数,下标类比ASCII码
#include <iostream>
#include <string>
#include <cstring>
 
using namespace std;
int main()
{
    int count[200]={0};
    string str;
    getline(cin,str);
    int len=str.length();
    int i,j,k=-1;        // 如果没有 则返回-1;所以k=-1;
     
    for (i=0;i<len;i++) {
        count[str[i]]++; //统计每个字母出现的次数
    }
 
    for (j=0;j<len;j++) {
        if (count[str[j]]==1) {
            k=j;
            break;
        }
    }
    cout<<k;
    return 0;
}
链接:https://www.nowcoder.com/questionTerminal/d370c322d06945a5901e8436d1e2e681?orderByHotValue=1&page=1&onlyReference=false
来源:牛客网

public static void main(String[] args) {
        String string;
        Scanner scanner=new Scanner(System.in);
        string=scanner.nextLine();
   
        char ch[]=string.toCharArray();

        Map<Character, Integer> map=new LinkedHashMap<Character, Integer>();
        for (int i=0;i<ch.length;i++) {
            if(map.containsKey(ch[i])) {
                char key=ch[i];
                int value=map.get(ch[i]);
                value++;
                map.put(key, value);
            }else {
                map.put(ch[i], 1);
            }
        }
        Set<Map.Entry<Character, Integer>> entrySet=map.entrySet();
        for (Map.Entry<Character, Integer> entry : entrySet) {
            if(entry.getValue()==1) {
                System.out.println(entry.getKey());
                break;
            }
        }
        
    }
链接:https://www.nowcoder.com/questionTerminal/d370c322d06945a5901e8436d1e2e681?orderByHotValue=1&page=1&onlyReference=false
来源:牛客网

function findFirst (str) {
    let length = str.length;
    for(let i = 0; i < length; i++) {
        if (str.indexOf(str[i]) === str.lastIndexOf(str[i])) {
            return str[i];
        }
    }
    return undefined;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值