코딩테스트 공부
[LeetCode] Reverse Prefix of Word - 자바스크립트 0617
codevil
2022. 6. 17. 12:49
https://leetcode.com/problems/reverse-prefix-of-word/submissions/
Reverse Prefix of Word - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이
1. 주어진 word에 ch가 없으면 return ch
if (!word.includes(ch)) return word
2. word안 에서의 ch의 index를 구한다
const chIndex = word.indexOf(ch)
3. 0부터 chIndex까지의 문자를 slice한다. 이때 slice는 맨뒤에 범위가 본인을 포함하지 않기 때문에 chIndex+1로 마지막에 인덱스를 넣는다
4. 3에서 구한 것을 revsere한다. revserse는 문자에서 바로 사용할 수 없으니 split("").revserse().join("")을 사용한다
let prefix = word.slice(0, chIndex + 1).split("").reverse().join("")
5. 남아 있는 것을 구하고 4번에서 구한것과 붙인뒤 return 한다
const rest = word.slice(chIndex + 1)
return prefix + rest
전체풀이
var reversePrefix = function (word, ch) {
if (!word.includes(ch)) return word
const chIndex = word.indexOf(ch)
let prefix = word.slice(0, chIndex + 1).split("").reverse().join("")
const rest = word.slice(chIndex + 1)
return prefix + rest
};