Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contains only lowercase English letters.
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.AskGif.Easy.String
{
public class FirstUniqCharSoln
{
public int FirstUniqChar(string s)
{
var map = new Dictionary<char, int>();
for(int i=0; i < s.Length; i++)
{
if (map.ContainsKey(s[i]))
{
map[s[i]]++;
}
else
{
map.Add(s[i], 1);
}
}
for (int i = 0; i < s.Length; i++)
{
if (map[s[i]] == 1)
{
return i;
}
}
return -1;
}
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Unit Tests:
using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingUnitTest.Easy.String
{
[TestClass]
public class FirstUniqCharSolnTests
{
[TestMethod]
public void FirstUniqCharSoln_First()
{
var s = "leetcode";
var output = 0;
var res = new FirstUniqCharSoln().FirstUniqChar(s);
Assert.AreEqual(res, output);
}
[TestMethod]
public void FirstUniqCharSoln_Second()
{
var s = "loveleetcode";
var output = 2;
var res = new FirstUniqCharSoln().FirstUniqChar(s);
Assert.AreEqual(res, output);
}
}
}



