Leetcode Algorithm

박영호·2021년 4월 1일

Today(04/01) Algorithm

1389. Create Target Array in the Given Order

Example 1:

Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]

Example 2:

Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
Explanation:
nums index target
1 0 [1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]

Example 3:

Input: nums = [1], index = [0]
Output: [1]

code

var createTargetArray = function(nums, index) {
  let arr = [];

    for (let i = 0; i < nums.length; i++) {
      arr.splice(index[i], 0, nums[i])
    }
  return arr;
}

1221. Split a String in Balanced Strings

Example 1:

Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.

Example 2:

Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.

Example 3:

Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".

Example 4:

Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'

code

var balancedStringSplit = function(s) {
    let length = s.length
    let rcnt = 0;
    let ccnt = 0;
    let count =0;
  
    for(let i = 0; i < s.length; i++) {
      (s[i] === 'R') ? rcnt += 1 : ccnt += 1;   
        if(rcnt === ccnt) {
          count += 1;
        } 
    }
  return count;
};

1684. Count the Number of Consistent Strings

Example 1:

Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
Output: 2
Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.

Example 2:

Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
Output: 7
Explanation: All strings are consistent.

Example 3:

Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
Output: 4
Explanation: Strings "cc", "acd", "ac", and "d" are consistent.

code

var countConsistentStrings = function(allowed, words) {
    let allowedArr = allowed.split("")
    return words.filter(word => {
        return word.split("").filter(w => !allowedArr.includes(w)).length === 0
    }).length
};
profile
무언가에 호기심이 생기면 적극적이고 재밌게 그걸 해결해내고 싶어하는 프론트 엔드 개발자 입니다 .

0개의 댓글