题目:给定一个字符串s,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回-1。

    1. functionfirstUniqChar(s: string): number {
    2. consthash=newMap();
    3. constarray=s.split("");
    4. array.forEach((item, index) => {
    5. if (hash.has(item)) {
    6. hash.set(item, {
    7. index,
    8. num: hash.get(item).num+1,
    9. });
    10. } else {
    11. hash.set(item, {
    12. index,
    13. num: 1,
    14. });
    15. }
    16. });
    17. letreturnData=-1;
    18. try {
    19. hash.forEach((item) => {
    20. if (item.num===1) {
    21. returnData=item.index;
    22. thrownewError("success");
    23. }
    24. });
    25. } catch (e) {
    26. if (e.message!=="success") {
    27. console.log("error");
    28. }
    29. }
    30. returnreturnData;
    31. }
    functionfirstUniqChar2(s: string): number {
      for (leti=0; i<s.length; i++) {
        if (s.indexOf(s[i]) ===s.lastIndexOf(s[i])) {
          returni;
        }
      }
      return-1;
    }