문자열 내에서 탐색하고자 하는 문자의 위치를 알 수 있는 indexOf()
와 lastIndexOf()
를 사용하여 값을 찾았다.
function solution(wallpaper) {
var answer = [];
const INF = 55;
var lux = INF, luy = INF, rux = 0, ruy=0;
// lux = 가장 작은 나온 #의 x좌표
// luy = 가장 작게 나온 #의 y좌표
// rux = 가장 큰 나온 #의 x좌표
// ruy = 가장 크게 나온 #의 y좌표
wallpaper.map((row,i)=>{
tempX = row.indexOf('#');
if(tempX !== -1){
lux = Math.min(lux, tempX);
luy = Math.min(luy, i);
}
tempX = row.lastIndexOf('#');
if(tempX !== -1){
rux = Math.max(rux, tempX);
ruy = Math.max(ruy, i);
}
})
return [luy, lux, ruy+1, rux+1];
}
String.prototpye.indexOf()
str.indexOf(searchValue[, fromIndex])
String.prototpye.lastIndexof()
*Taemin Jang 님의 풀이를 참고하였습니다.
가능한 모든 좌표를 모아 그 안에서 최대, 최소값을 구한다
function solution(wallpaper) {
var left = [];
var top = [];
var right = []
var bottom = [];
wallpaper.forEach((row,i) => {
[...row].forEach((file,idx) => {
// 정답이 될 수 있는 모든 index값 저장
if(file === "#") {
left.push(i)
top.push(idx)
right.push(i + 1)
bottom.push(idx + 1)
}
})
})
return [Math.min(...left), Math.min(...top), Math.max(...right), Math.max(...bottom)]
}
...
를 이용하여 문자열을 배열로 변환할 수 있다.