找出字符串中第一个只出现一次的字符(题面已经更新)/华为机试(C/C++)

本文介绍了一种算法,用于从输入的字符串中找出并返回第一个只出现一次的字符。若字符串中所有字符都重复出现,则返回-1。算法通过遍历字符串,使用数组记录每个字符的出现次数及首次出现的位置,从而高效地找到目标字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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

输入描述:

输入一个非空字符串

输出描述:

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

示例1

输入

asdfasdfo

输出

o

代码:

//第五十七题  找出字符串中第一个只出现一次的字符(题面已经更新)
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str;
	while (cin >> str)
	{
		int a[26]{ 0 };
		int aP[26]{ 0 };
		int A[26]{ 0 };
		int AP[26]{ 0 };
		size_t sLength = str.length();
		for (int i = 0; i < sLength; i++)
		{
			if (isupper(str[i]))
			{
				if (A[str[i] - 'A'] == 0)
					AP[str[i] - 'A'] = i;
				A[str[i] - 'A']++;
			}	
			else
			{
				if (a[str[i] - 'a'] == 0)
					aP[str[i] - 'a'] = i;
				a[str[i] - 'a']++;
			}
				
		}
		int mun = 1;
		int iMinId = 0;
		int iMinPosition = 1000;
		for (int i = 0; i < 26; i++)
		{
			if (A[i] == 1)
			{
				if (iMinPosition > AP[i])
				{
					iMinPosition = AP[i];
					iMinId = i;
				}
				mun = 0;
			}
			if (a[i] == 1)
			{
				if (iMinPosition > aP[i])
				{
					iMinPosition = aP[i];
					iMinId = i;
				}
				mun = 0;
			}
		}
		if (mun)
			cout << -1 << endl;
		else
		{
			if (aP[iMinId] == iMinPosition)
			{
				char temp = iMinId+ 'a';
				cout << temp << endl;
			}
			else
			{
				char temp = iMinId + 'A';
				cout << temp << endl;
			}
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值