JS Questions

by dpnminh

JavaScript

//Two Sum - LeetCode #1
//Given an array of integers, return indices of the two numbers such that they add up to a specific target.
//You may assume that each input would have exactly one solution, and you may not use the same element twice

var twoSum = function(nums, target) {
  var arrIndices = [];
  var mapOfMatches = {};

  for (var i = 0; i < nums.length; i++) {
    var num = nums[i];

    if (mapOfMatches[num] === undefined) {
      var matchNum = target - num;

      if (mapOfMatches[matchNum] === undefined) {
        mapOfMatches[matchNum] = i;
      }
    } else {
      arrIndices = [mapOfMatches[num], i];
      break;
    }
  }

  return arrIndices;
};


//Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
//The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

/**
 * @param {string} s
 * @return {boolean}
 */
var validPalindrome = function(s) {
  return checkPalindromeII(s, 1);

};

function checkPalindromeII(str, level) {
  if (str === "" || str.length >= 50000) return false;

  if (level === 0) return getReverse(str) === str;

  var left = 0,
    right = str.length - 1;

  while (left < right) {
    if (str[left] !== str[right]) {
      return checkPalindromeII(str.substring(left + 1, right + 1), level - 1) || checkPalindromeII(str.substring(left, right), level - 1);
    }

    left++;
    right--;
  }

  return true;
}

function getReverse(str) {
  var reversed = "";

  for (var i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }

  return reversed;
}

//Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

//For example,
//"A man, a plan, a canal: Panama" is a palindrome.
//"race a car" is not a palindrome.

//Note:
//Have you consider that the string might be empty? This is a good question to ask during an interview.

//For the purpose of this problem, we define empty string as...