Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit series activities – click on the task to see the details of the activities.

A,Topic describes

  • Given a stringsTo findIts first non-repeating character and returns its index. If it does not exist, return- 1 。
  • Example 1:
    • Enter: s = “leetcode”
    • Output: 0
  • Example 2:
    • Enter: s = “loveleetCode”
    • Output: 2
  • Example 3:
    • Enter: s = “aABB”
    • Output: 1
  • Tip:
    • 1 <= s.length <= Math.pow(10, 5)
    • sContains only lowercase letters

Ii. Analysis of Ideas:

  • To find the first character that is not repeated, most likely iterating through the string
    • First of all, the given string into an array, js array traversal or more convenient
    • It then iterates through the array to determine if the current item is unique in the array. If so, it returns the index of the current item. If not, it iterates through the next item until the entire array has been searched, and returns -1 if not
  • Determines whether the current item is unique
    • One is just using arraysindexOfandlastIndexOfMethod to determine, only traverse once

Iii. AC Code:

function firstUniqChar(s: string) :number {
    if(s.length === 1) return 0;
    let strArr = s.split(' ');
    for(let i = 0; i < strArr.length; i++){
        if(strArr.indexOf(strArr[i]) === strArr.lastIndexOf(strArr[i])){
            return i
        }
    }
    return -1
};
Copy the code

Iv. Summary:

  • Notice that the array length is zero1In this case, it is impossible to repeat items
  • This should be less code, the solution area to see other big guy’s code, feel more than this, there are other simple methods, interested can go to the solution area to see