본문 바로가기

Algorithm & World Class

(Algorithm) Microsoft Online Assessment Questions

You are given an array S consisting of N strings. Every string is of the same length M. Your task is to find a pair of strings in array S, such that there exists a position in which both of the strings have the same letter. Both the index in array S and the positions in the strings are numbered from zero. 

 

For example, given S = ["abc", "bca", "dbe"], string 0 ("abc") and string 2 ("dbe") have the same letter 'b' in position 1. On the other hand, for strings "abc" and "bca" there does not exist a position in which they have the same letter. = Write a function: vector solution (vector &S); that, given a zero indexed array S of N strings, returns an array describing a pair of strings from S which share a common letter at some index. If there is no such pair, the function should return an empty array. If there is more than one correct answer, the function can return any of them.

 

The result should be represented as an array containing three integers. The first two integers are the indexes in S of the strings belonging to the pair. The third integer is the position of the common letter. For S = ["abc", "bca", "dbe"), as above, the result array should be represented as [0, 2, 1]. Another correct answer is [2, 0, 1], as the order of indexes of strings does not matter.

 

return 값이 [0, 2, 1] 일때

처음 두 정수는 쌍에 속하는 문자열 S에 있는 인덱스이고

세번째 정수는 공통 문자의 위치이다.

 

S = ["abc", "bca", "dbe"]의 경우 위와 같이 결과 배열은 [0, 2, 1)로 표현되어야 하고

또 다른 정답은 [2, 0, 1] 이다. 문자열의 인덱스의 순서는 고려할 필요가 없다.

 

mine

function solution(S) {
  let result = [];
  let isFound = false;
  
  for(let i = 0; i < S.length; i++) {
    let currentString = S[i];
    
    for(let j = i + 1; j < S.length; j++) {
      let chkString= S[j];
      
      for(let p = 0; p < currentString.length; p++) {
        if(currentString.charAt(p) === chkString.charAt(p)) {
          // 조건을 만족하는 경우를 찾는 순간 바로 break를 통해 for문에서 빠져나온다.
          result[0] = i;
          result[1] = j;
          result[2] = p;
          isFound = true;
          break;
        }
      }
      if(isFound) break;
    }
    if(isFound) break;
  }
  return result
}

let output = solution(["abc","bca","dbe"])
console.log(output)