C++练习12:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1

C++练习12:找到给定字符串的第一个不重复字符,并返回其索引;若不存在则返回 -1。

题目

给定一个字符串及其长度,找到其第一个不重复的字符,并返回其索引;若不存在,则返回 -1。

示例:
Input:
8
leetcode
Output:0

Input:
13
sloveleetcdes
Output:2

方法1(待改进)

#include <iostream>
using namespace std;

int main(){
	
	string s;
	cout << "请输入一个字符串:";
	cin >> s;
	
	int cout[256]={0};
    int len = s.length();
    
    //统计每个字符出现的次数
    for (int i=0;i<len;i++){
        cout[s[i]]+=1;
    }
    
    //遍历找到出现一次的字符,并返回索引。否则,返回-1
    for(int i=0;i<len;i++){
        if(cout[s[i]]==1){
        	return i;
		}
    }
    return -1;	
} 

有点问题,有待更新修正

方法2(正解)

#include<iostream>
using namespace std;

int firstUniqChar(char str[], int n) 
{
	int map[26] = { 0 };
	for (int i = 0; i < n; i++){
		map[str[i] - 'a']++;
	}
	
	for (int i = 0; i < n; i++){
		if (map[str[i] - 'a'] == 1){
			return i;
		}
	}
	return -1;
}

int main() 
{
	int n;
	char str[500];
	cout << "请输入字符串长度: ";
	cin >> n;
	cout << "请输入字符串: "; 
	cin >> str;
	cout << firstUniqChar(str, n) << endl;
}

正解!

方法3

#include <iostream>
using namespace std;

int main(){
	
	string s;
	cout << "请输入一个字符串:";
	cin >> s;
	
	int i, j, count = 0;
	
	if(s.size() == 0){
		return -1;
	}
	for (i = 0; i < s.size(); i++)
	{
		for (j = 0; j < s.size(); j++)
		{
			cout << s[i] << " ";
			cout << s[j] << endl;
			if (s[i] == s[j])
			{
				count++;
			}
            if(count>1)
                break;
		}
		if (count ==1 )
			return i;
		count = 0;
	}
	return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

调参侠鱼尾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值