387. First Unique Character in a String

2018/04/13 leetcode 共 817 字,约 3 分钟

Title

the problem link

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.

题目大意:返回仅出现一次的字符位置的索引

这个是CVTE二面让做的哈哈哈哈哈

处女面就是cvte了,结果一面二面终面都过了,这个题就是二面做的,还是挺简单的,一次ac

Solution

//cpp:
class Solution {
public:
	int firstUniqChar(string s) {
		int nums[256] = { 0 };
		for (int i = 0; i < s.length(); i++) {
			nums[s[i]]++;
		}
		for (int i = 0; i < s.length(); i++) {
			if (nums[s[i]] == 1)
				return i;
		}
		return -1;
	}
};

看discuss,看到了一个pair的新用法

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, pair<int, int>> m;
        int idx = s.size();
        for (int i = 0; i < s.size(); i++) {
            m[s[i]].first++;
            m[s[i]].second = i;
        }
        for (auto &p : m) {
            if (p.second.first == 1) idx = min(idx, p.second.second);
        }
        return idx == s.size() ? -1 : idx;
    }
};

Search

    Table of Contents