Algorithm #02 "1st non-repeated char?"

filoscoderΒ·2019λ…„ 11μ›” 22일
0

Toy Algorithm

λͺ©λ‘ 보기
2/7
post-thumbnail

πŸ‡ΊπŸ‡Έ Given an arbitrary input string, return the first nonrepeated character in the string.

πŸ‡¦πŸ‡· Dado una palabra u oracion aleatoria, retorne la primer letra no repetida en dicha palabra u oracion.

πŸ‡°πŸ‡· μž„μ˜ λ¬Έμžμ—΄μ„ 인자둜 받을 경우 λ¬Έμžμ—΄μ˜ 첫 번째 비쀑볡 문자λ₯Ό λ°˜ν™˜ν•˜μ‹­μ‹œμ˜€.

Example:

stNonRepChar('ABA');    // => 'B'
stNonRepChar('AACBDB'); // => 'C'

# START [ here ] 🏁

var stNonRepChar = function(str) {
  // Your CODE
}

// Test
stNonRepChar("AACBDB");

# Javascript solution πŸ†

  • Run it on your browser console window (F12) πŸ–₯
  • Please feel free to add your preference language solution πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦
  • Do your best to complete the problem 🎭
  • if you can't beat this the solution is below 😱

solution πŸ‘‡

.
.
.
.
.
.
.
.
.
.
.

SOLUTION #1

var stNonRepChar = function(str) {
  var counter = {};
  for (let i = 0; i < str.length; i++) {
    if (counter[str[i]]) {
      counter[str[i]]++;
    } else {
      counter[str[i]] = 1;
    }
  }
  for (let i = 0; i < str.length; i++) {
    if (counter[str[i]] === 1) {
      return str[i];
    }
  }
}

// Test
console.log(stNonRepChar("AACBDB"));

SOLUTION #2

var stNonRepChar = function(str) {
  for (let char of str) {
    if (str.match(new RegExp(char, "gi")).length == 1) {
      return char;
    }
  }
}

// Test
console.log(stNonRepChar("AACBDB"));

SOLUTION #3

var stNonRepChar = function(str) {
  var strTrim = str.split("");
  var result = "";
  var counter = 0;

  for (var x = 0; x < strTrim.length; x++) {
    counter = 0;

    for (var y = 0; y < strTrim.length; y++) {
      if (strTrim[x] === strTrim[y]) {
        counter += 1;
      }
    }
    if (counter < 2) {
      result = strTrim[x];
      break;
    }
  }
  return result;
}

// Test
console.log(stNonRepChar("AACBDB"));
profile
Never gets bored of making mistakes and wonder why is that

0개의 λŒ“κΈ€