Skip to content

Commit

Permalink
Implement nonrepeatedCharacter.js
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Jan 3, 2015
1 parent 923666d commit f2d3a1a
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions nonrepeatedCharacter/nonrepeatedCharacter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,30 @@
* firstNonRepeatedCharacter('AACBDB'); // => 'C'
*/

var firstNonRepeatedCharacter = function(string) {
// TODO: your solution here
var firstNonRepeatedCharacter = function (string) {
// solution will have to be at least O(n) because you have to go through all characters
// in string before you know whether any character is repeated
if ( typeof string !== 'string' ) throw new Error('Must provide a string');
if ( string.length <= 0 ) throw new Error('String must be at least a character long');

var hash = {};
var len = string.length;
var i;



for (i = 0; i < len; i += 1) {
if ( hash[ string[i] ] === void 0 ) {
hash[ string[i] ] = true;
} else if ( hash[ string[i] ] ) {
hash[ string[i] ] = false;
}
}

i = 0;
while ( !hash[ string[i] ] ) {
i += 1;
}

return string[i];
};

0 comments on commit f2d3a1a

Please sign in to comment.