Saturday, 16 October 2021

First Unique Character in a String - LeetCode 387

 Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

 

Example 1:

Input: s = "leetcode"
Output: 0

Example 2:

Input: s = "loveleetcode"
Output: 2

Example 3:

Input: s = "aabb"
Output: -1

 

Solution:

class Solution {

    public int firstUniqChar(String s) {

        

        Map<Character,Integer> map=new HashMap<>();

        int result=-1,count=0;

        

        for(int i=0;i<s.length();i++){

            char ch=s.charAt(i);

            if(map.containsKey(ch))

                map.put(ch,map.get(ch)+1);

            else

                map.put(ch,1);

        }

       

        for(int i=0;i<s.length();i++){

            char ch=s.charAt(i);

            if(map.get(ch)==1){

                return i;

            }

            

        }

        

        return -1;

    }

}

No comments:

Post a Comment

Random password generator in Java

       Random password generator in Java Source code: mport java.io.*; import java.util.*; public class Main { public static void main(Str...