jeudi 5 août 2021

First Unique Character In a String-Leetcode

I have tried out 387.First Unique Character In A string

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

I have been trying this problem. I thought we will pick one by one all the characters and check if a repeating character exists break from the loop. And if not then return that index.I have thought over a solution which I believe is not the most efficient way but I want to know the how can I solve this problem with the approach given below:

public int firstUniqChar(String s) {
  for(int i=0;i<s.length();i++){
      for(int j=i+1;j<s.length();j++){
          if(s.charAt(i)==s.charAt(j)){
              break;
          }
          
      }
      
  }
    return -1;
}

I'm confused how to return the index.I'm unable to find the logic after:

for(int j=i+1;j<s.length();j++){
              if(s.charAt(i)==s.charAt(j)){
                  break;
              }
              
          }

If anyone can help me find out the logic here.

Aucun commentaire:

Enregistrer un commentaire