C# LinkedHashMap O(N) Single Pass


  • 0
    F
       public class Solution {
        public int FirstUniqChar(string s) {
        var order = new LinkedList<int>();
        var map = new Dictionary <char, LinkedListNode<int>>();
        
        for (int i = 0; i < s.Length; i++)
        {
            if (map.ContainsKey(s[i]))
            {
                var node = map[s[i]];
                if (node != null) order.Remove(node);
                map[s[i]] = null;
            }
            else
            {
                var newNode = new LinkedListNode<int>(i);
                map[s[i]] = newNode;
                order.AddLast(newNode);
            }
        }
        
        if (order.Count == 0) return -1;
        return order.First.Value;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.