First Unique Character in a String

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

Example:

Input:  str="loveol"
Output: 2

Approach

Java

public class FirstUniqueCharacterInString {
    public static void main(String[] args) {
        String str = "loveol";
        System.out.println(firstUniqChar(str));
    }

    static int firstUniqChar(String s) {
        int f[] = new int[26];
        for (int i = 0; i < s.length(); i++) {
            f[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < s.length(); i++)
            if (f[s.charAt(i) - 'a'] == 1)
                return i;
        return -1;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int firstUniqChar(string s
{
        int f[26]={0};
        for(int i=0;i<s.size();i++)
        {
            f[s[i]-'a']++;
        }
        for(int i=0;i<s.size();i++)
            if(f[s[i]-'a']==1)
                  return i;
        return -1;
}
int main()
{
    string str="loveol";
    cout<<firstUniqChar(str);
    return 0;
}


No comments:

Post a Comment