Leetcode problem solution-the first unique character in the string & valid letter dyslexia & verify palindrome string

The first unique character in the string

Code

var firstUniqChar = function(s) {
    
    
    let map = {
    
    };
    let t = [];
    for(let i=0,l=s.length;i<l;i++){
    
    
     if(map[s[i]]===undefined){
    
    
            map[s[i]] =t.length;
            t.push(i);
        }else{
    
    
            t[map[s[i]]] = null;
        }
    }
    for(let i=0,l=t.length;i<l;i++){
    
    
        if(t[i]!=null){
    
    
            return t[i]
        }   
    }
    return -1
};

Ideas

Use the map table
keyvalue to represent the letter.
valueStore the position of the letter.
An auxiliary array. t
If the letter is not in the map table, push the position to t[]. If the map exists, set the corresponding position in t to null.
Finally, just find the first one in the auxiliary array t The number that is not null is the desired position

Valid letter variants

Code

var isAnagram = function(s, t) {
    
    
    if(s.length!==t.length){
    
    
       return false
    }
    if(s===t){
    
    
        return true
    }
    let l = s.length;
    let map1 = {
    
    };
    let map2 = {
    
    };
    for(let i = 0;i<l;i++){
    
    
        if(!map1[s[i]]){
    
    
            map1[s[i]] =1 
        }else{
    
    
            map1[s[i]] +=1
        }
        if(!map2[t[i]]){
    
    
            map2[t[i]] =1 
        }else{
    
    
            map2[t[i]] +=1 
        }
    }
    for (let item in map1){
    
    
        if(!map2[item]||map1[item]!=map2[item]){
    
    
            return false
        }
    }
    return true
};

Ideas

There are only 26 letters in the map. First map the two strings to the map table separately,
as long as you judge whether the two map tables are the same, the
maximum number of times is l*2+26 times

Verify palindrome string

Code

var isPalindrome = function(s) {
    
    
  s = s.replace(/[^0-9a-zA-Z]/g, '').toLowerCase();
  let l = 0, r = s.length - 1;
  while (l < r) {
    
    
    if (s[l]!==s[r]) {
    
    
      return false
    }
    l++
    r--
  }
  return true
};

Ideas

[^0-9a-zA-Z]Negative value means
double pointer except 0-9a-zA-Z, one pointer is from front to back and the other is from back to front

Guess you like

Origin blog.csdn.net/weixin_38616850/article/details/106505846