return first non repeating character in a string
I had to solve this question in which given a string, i had to return the first non repeating character 开发者_开发问答present in the string.
I solved it using hashtable and wrote a method which takes a constant reference to the string and returns the first non repeating character. However, when there is no non repeating character present in the string, i return -1 and in the main program i check as follows
char c = firstNonRepeating( word );
if (static_cast<int> (c) == -1)
cout<<"no non repeating character present\n";
else
cout<<c<<endl;
is that the correct way to return -1 when required character is not present?
You can return
simply 0
. Because logically, in any case 0
is the first non-repeating character in any nul-terminated string !
I think returning -1
is error prone because you do a casting to int
and moreover 255
is also a valid character.
It may be a matter of style, but I would rather go for something like:
char c;
bool result = getFirstNonRepeating(word, c);
if (result)
cout << "no non repeating character present\n";
else
cout << c << endl;
Where c
's value after the call is unspecified if getFirstNonRepeating
returns false
.
That way, there is no ambiguity between the return value and the result (or failure) of the operation, and your getFirstNonRepeating
function can work even for '\0'
or 0xFF
characters if you ever need to change the logic.
Just one more option: to be more similar to STL algorithms you may return iterator to the first non-repeating character, in case of its absence simply return string.end().
I have used HashMap to count characters
FirstNonRepeating(String s){
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
count.put(c, count.getOrDefault(c, 0) + 1);
}
// find & print the index position
for (int i = 0; i < n; i++) {
if (count.get(s.charAt(i)) == 1)
System.out.println(i);
}
精彩评论