'2019/08/29'에 해당되는 글 2건

  1. 2019.08.29 Check Permutation
  2. 2019.08.29 Is Unique?
JavaScript2019. 8. 29. 20:30

Given two strings, write a method to decide if one is a permutation of the other.

 


var checkPermute = function(stringOne, stringTwo) {
  // if different lengths, return false
  if (stringOne.length !== stringTwo.length) {
    return false;
  // else sort and compare 
  // (doesnt matter how it's sorted, as long as it's sorted the same way)
  } else {
    var sortedStringOne = stringOne.split('').sort().join('');
    var sortedStringTwo = stringTwo.split('').sort().join('');
    return sortedStringOne === sortedStringTwo;
  }
};

// Tests
console.log(checkPermute('aba', 'aab'), true);
console.log(checkPermute('aba', 'aaba'), false);
console.log(checkPermute('aba', 'aa'), false);

Posted by 섹개

댓글을 달아 주세요

JavaScript2019. 8. 29. 20:03

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

 


var allUniqueChars = function(string) {
  
  
  // O(n^2) approach, no additional data structures used
  // for each character, check remaining characters for duplicates
  for (var i = 0; i < string.length; i++) {
    for (var j = i + 1; j < string.length; j++) {
      if (string[i] === string[j]) {
        return false; // if match, return false
      }
    }
  }
  return true; // if no match, return true
};

/* TESTS */
// log some tests here

console.log(allUniqueChars("abcd")); // true
console.log(allUniqueChars("aabbcd")); // false

Posted by 섹개

댓글을 달아 주세요