Given a string
s
, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'
.
Example
- For
s = "abacabad"
, the output should be
firstNotRepeatingCharacter(s) = 'c'
.There are2
non-repeating characters in the string:'c'
and'd'
. Returnc
since it appears in the string first. - For
s = "abacabaabacaba"
, the output should be
firstNotRepeatingCharacter(s) = '_'
.There are no characters in this string that do not repeat.
Input/Output
- [time limit] 500ms (cpp)
- [input] string sA string that contains only lowercase English letters.Guaranteed constraints:
1 ≤ s.length ≤ 105
. - [output] charThe first non-repeating character in
s
, or'_'
if there are no characters that do not repeat.
My this solution:
char firstNotRepeatingCharacter(std::string s)
{
char temp = ' ';
for (int i = 0; i < s.length(); i++) {
for (int g = 0; g < s.length(); g++) {
if (s.length() == 1) {
temp = s[0];
}
else if (i == g) {
continue;
}
else if (s[i] == s[g]) {
temp = '_';
break;
}
else {
temp = s[i];
}
}
if (temp != '_')
return temp;
}
return temp;
}
Comments
Post a Comment