Given a string, find its first non-repeating characters, and returns its index. If not, it returns -1.

topic:

Given a string, find its first non-repeating characters, and returns its index. If not, it returns -1.

 
 

Case:

 
 

s = "leetcode"
return 0.

 
 

s = "loveleetcode",
return to 2.






Solution one: a little violence, the main idea was thrown out after itself, use indexOf inquiry to find out if there are duplicate values, there is no direct return current index
/ *
* * @param {String} S * @return Number The {} * / var firstUniqChar = function (S) { var len = s.length; for ( var I = 0; I <len; I ++ ) { var STR = S, Test = str.split ( '' ); test.splice (I, . 1 ) ; var Sub = test.indexOf (S [I]); IF (Sub === -1) return I; } return -1 ; };
Solution two: 
the idea here is to use intermediate variable as a counter to record the number of repeats. Repeat the event directly out of the loop, to find the next number of matches. And so on, not a repeat of the first direct return current index breaks all the event

/ *
* * @param {String} S * @return {Number} * / var firstUniqChar = function (S) { var len = s.length;
  // need to compare the value of each cycle
for ( var I = 0; I <len; I ++ ) {
    // introduced counter
var Sub = 0 ;
    // for each cycle of the reference value other than itself
for ( var 0 = J; J <len; J ++ ) {
        // encounters duplicate itself and not directly out counter counts the time and the comparison cycle
IF (S [I] === S [J] && J == I) {!
          sub++;
          break;
        } }
if(sub === 0) return i; } return -1; };

In addition to the above-mentioned solution, solution-based think of two ideas solution III.

  That is the first in a string of repeated characters with the first character to extract and return new string after extraction, an extract, the extract know it encounters the first character can not duplicate values, use indexOf inquiry this string returns its index, will not be repeated or no direct return -1

Guess you like

Origin www.cnblogs.com/jjq-exchange/p/11199101.html