You are given a string, find its first non-repeating character?
Algorithm:
1) Scan the string from left to right and construct the count array.
2) Again, scan the string from left to right and check for count of each
character, if you find an element who’s count is 1, return it.
#include<stdlib.h> #include<stdio.h> #define NO_OF_CHARS 256 /* The function returns index of first non-repeating character in a string */ int getFirstNonRepeating(char *str) { int *count = (int *)calloc(sizeof(int), NO_OF_CHARS); int i; for (i = 0; *(str+i); i++) count[*(str+i)]++; int index = -1; for (i = 0; *(str+i); i++) { if(count[*(str+i)] == 1) { index = i; break; } } return index; }
Time complexity: O(N)
consider arrayoutofindex case here. rather than puting directly using *(str+i) like this use *(str+i)-offset, here offset might be 65(ascii value if A or 97 ascii value of a) if the string contains only alphabets.
public class nonRep {
public static void main(String[] args) {
String s1=”asdfas” ;
char [] arr=new char[256];
for(int i=0;i<s1.length();i++)
{
arr[s1.charAt(i)]++;
}
for(int i=0;i<256;i++)
{
if(arr[i] == 1)
{
System.out.printf("%c",i);
break;
}
}
}
}
good answer tarun
s1.charAt(i) returns a character how can a character be index of an array please explain