本篇同步发布於Blog:[解题] LeetCode - 387 First Unique Character in a String
LeetCode
387 - First Unique Character in a String
https://leetcode.com/problems/first-unique-character-in-a-string/
给一个字串s,求它第一个只出现一次的字元的索引值,假如找不到则回传-1。题目保证只有小写英文字元。
比如范例输入s = "leetcode",l是第1个出现且只出现一次的字元,所以回传它的索引值0。
建立2维度的阵列(或者List),第1维度是字母a - z的索引值,第2维度是该字元的出现位置。s字串从头扫描一遍,记录每个字元的出现位置。最後再从2维阵列找出现位置只有1个且位置是最小的。
难度为Easy
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int firstUniqChar(string s) {
vector<vector<int>> checkChars(26);
for(int i = 0 ; i < s.length();++i){
checkChars[s[i] - 'a'].push_back(i);
}
bool isUniqueFind = false;
int minIndex = 99999999;
for(int i = 0 ; i < 26;++i){
if(checkChars[i].size() == 1){
isUniqueFind = true;
if(checkChars[i][0] < minIndex){
minIndex = checkChars[i][0];
}
}
}
if(isUniqueFind){
return minIndex;
}
else{
return -1;
}
}
};
int main() {
Solution sol;
cout << sol.firstUniqChar("leetcode") << endl;
cout << sol.firstUniqChar("aabbcc") << endl;
cout << sol.firstUniqChar("abcabcd") << endl;
return 0;
}
using System;
using System.Collections.Generic;
namespace LeetCode387
{
public class Solution {
public int FirstUniqChar(string s) {
List<List<int>> checkChars = new List<List<int>>();
for(int i = 0 ; i < 26;++i){
checkChars.Add(new List<int>());
}
for(int i = 0 ; i < s.Length;++i){
checkChars[s[i] - 'a'].Add(i);
}
bool isUniqueFind = false;
int minIndex = 99999999;
for(int i = 0 ; i < 26;++i){
if(checkChars[i].Count == 1){
isUniqueFind = true;
if(checkChars[i][0] < minIndex){
minIndex = checkChars[i][0];
}
}
}
if(isUniqueFind){
return minIndex;
}
else{
return -1;
}
}
}
public class Program
{
public static void Main()
{
Solution sol = new Solution();
Console.WriteLine(sol.FirstUniqChar("leetcode"));
Console.WriteLine(sol.FirstUniqChar("aabbcc"));
Console.WriteLine(sol.FirstUniqChar("abcabcd"));
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/300-399/387.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/300-399/387.cs
昨天提到,当Azure Hyper-V需要被其它Azure VM内网存取的时候, 该如何调整呢?内网...
前言: 昨天跟大家介绍了如何把你写好的网页透过firebase deploy到网路上,但目前还只能透...
这个章节要开始建立「PWM 输出视窗」。 何谓 PWM 名为「脉冲宽度调变」(Pulse-width...
DAY8 MongoDB 批次操作(bulk wirte) 与 Operators bulk wri...
今天要主要来分享一下特性描述器。 特性描述器 (property descriptor) 在 ES...