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

#pragma once 
/*
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,
并返回它的位置, 如果没有则返回 -1(需要区分大小写).
*/
#include<iostream>
using namespace std;
/*
**自己实现方案,
*/
#if 0
static class Solution {
public:
	int FirstNotRepeatingChar(string str) {
		int str_count[52] = { 0 };
		int lenght = str.size();
		int ret = 0;
		char c = '0';
		int i = 0;
		while (i < lenght)
		{
			if (str[i] >= 'a'&&str[i] <= 'z')
				++str_count[str[i] - 'a'];
			else if (str[i] >= 'A'&&str[i] <= 'Z')
				++str_count[str[i] - 'A' + 32];
			++i;
		}
		for (i = 0; i < 52; ++i)
		{
			if (str_count[i] == 1)
				ret = i;
		}
		if (ret == 52) return -1;
		else if (ret < 32) c = ret + 'a';
		else c = ret + 'A' - 32;

		for (i = 0; i < lenght; ++i)
		{
			if (str[i] == c)
				return i;
		}

		return -1;
	}
};
#endif//自己实现臭代码

#if 1
#include<map>
class Solution {
public:
	int FirstNotRepeatingChar(string str) {
		map<char, int> mp;
		for (int i = 0; i < str.size(); ++i)
			mp[str[i]]++;
		for (int i = 0; i < str.size(); ++i){
			if (mp[str[i]] == 1)
				return i;
		}
		return -1;
	}
};

#endif//大神解法

猜你喜欢

转载自blog.csdn.net/jiaochiwuzui/article/details/81316277
今日推荐