C# solution using dictionary


  • 0
    E

    Not the bset solution but works fine

    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    public class Solution {
        
      public int FirstUniqChar(string s) {
                        ArrayList al = new ArrayList();
    
            char[] charArr;
            charArr=s.ToArray();
            Dictionary<char,int> dict= new Dictionary<char,int>();
    
            foreach( char c in charArr)
            {
                if(!dict.ContainsKey(c))
                {
                    dict.Add(c,1);
                    
                }
                else
                {
                  int value=dict[c];
                    value++;
                    dict[c] = value;
                }
            }
            
             Dictionary<char,int> uniqueValues= new Dictionary<char,int>();
    
            foreach( KeyValuePair<char,int> kvp in dict)
            {
                if(!uniqueValues.ContainsKey(kvp.Key) &&kvp.Value==1)
                {
                    uniqueValues.Add(kvp.Key,kvp.Value);
                    
                }
                
            }
            
           Dictionary<int,char> allValues= new Dictionary<int,char>();
            int keyStart=0;
            foreach( char c in charArr)
            {
                if(!allValues.ContainsKey(keyStart))
                {
                    allValues.Add(keyStart,c);
                    
                }
               keyStart++;
            } 
            foreach( KeyValuePair<int,char> kp in allValues)
            {
                if (uniqueValues.ContainsKey(kp.Value))
                {
                    al.Add(kp.Key);
                }
                
                
            }
             if (al.Count > 0)
             return Convert.ToInt32(al[0]);
             else
             return -1;
             
           
        }
    }
    

Log in to reply
 

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