LeetCode(387)First Unique Character in a String

Posted 逆風的薔薇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(387)First Unique Character in a String相关的知识,希望对你有一定的参考价值。

题目

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

分析

求给定字符串中第一个只出现一次的字符。 哈希思想。

代码

/*
387. First Unique Character in a String
*/

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>

using namespace std;
class Solution 
public:
	/*方法一,借助哈希表*/
	int firstUniqChar1(string s) 
		if (s.empty())
			return -1;

		vector<int> v(256, 0);
		int len = s.length();
		for (int i = 0; i < len; ++i)
			++v[s[i]];

		for (int i = 0; i < len; ++i)
			if (v[s[i]] == 1)
				return i;
		return -1;
	
	/*方法二:*/
	int firstUniqChar(string s) 
		if (s.empty())
			return -1;
		int len = s.length();
		map<char, int> sm;
		for (int i = 0; i < len; ++i)
		
			++sm[s[i]];
		//for

		for (int i = 0; i < len; ++i)
			if (sm[s[i]] == 1)
				return i;
		return -1;
	

	
;


以上是关于LeetCode(387)First Unique Character in a String的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode387. First Unique Character in a String

Leetcode-387 First Unique Character in a String

LeetCode_387. First Unique Character in a String

LeetCode - 387. First Unique Character in a String

[leetcode-387-First Unique Character in a String]

Leetcode 387: First Unique Character in a String