1. ๋ฌธ์
2. ํ์ด
3. ๋ค๋ฅธ ํ์ด

1. ๋ฌธ์
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
๋๊ฐ์ ๋ฌธ์์ด needle, haystack์ด ์ฃผ์ด์ง ๋, haystack์์ needle์ ์ฒซ๋ฒ์งธ ์ธ๋ฑ์ค๋ฅผ ๋ฐํํ๊ณ ,
needle์ด haystack์ ํ ๋ถ๋ถ์ด ์๋๋ผ๋ฉด -1์ ๋ฐํํ๋ค.
2. ํ์ด
const strStr = function(haystack, needle) {
if (needle.length === 0) return 0;
let index = -1;
if (haystack.includes(needle)) {
let firstLetter = needle.split(0, 1);
index = haystack.indexOf(firstLetter);
}
return index;
};
์๊ฐํ ๊ณผ์ ์ ๋ค์๊ณผ ๊ฐ๋ค.
- haystack์ด needled์ ํฌํจํ๊ณ ์๋์ง ํ์ธํ๋ค.
- ์๋๋ผ๋ฉด -1์ ๋ฐํํ๋ค.
- ํฌํจํ๊ณ ์๋ค๋ฉด needled์ ์ฒซ๋ฒ์งธ ๊ธ์๋ฅผ ์๋ผ์จ๋ค
- haystack์์ ์ฒซ๋ฒ์งธ ๊ธ์ ์ธ๋ฑ์ค์ ์์น๋ฅผ ์ฐพ์ ๋ฐํํ๋ค.
haystack์ด needle์ ํฌํจํ๊ณ ์๋์ง๋ฅผ ๋จผ์ ํ์ธํ๊ธฐ ์ํด includes ๋ฉ์๋๋ฅผ ์ด์ฉํ๋ค.
includes ๋ฉ์๋๋ ํ ๋ฌธ์์ด์ด ๋ค๋ฅธ ๋ฌธ์์ด์ ํฌํจ๋์ด์๋์ง๋ฅผ ํ๋จํด์ boolean ํํ๋ก ๋ฐํํ๋ ๋ฉ์๋๋ค.
ํฌํจ๋๋ค๋ฉด, split ๋ฉ์๋๋ฅผ ํตํด needle์ ์ฒซ๋ฒ์งธ ๊ธ์๋ฅผ ์๋ผ์์
indexOf ๋ฉ์๋๋ก ์ฒซ๋ฒ์งธ ๊ธ์์ ์ฒซ๋ฒ์งธ ์ธ๋ฑ์ค๋ฅผ ๊ฐ์ ธ์ ๋ฐํํ๋ค.
3. ๋ค๋ฅธ ํ์ด
const strStr = (haystack, needle) => {
if (needle === '' || needle === haystack) return 0;
if (haystack.length < needle.length) return -1;
for (let i = 0; i < haystack.length - needle.length + 1; i++) {
if (haystack[i] === needle[0]) {
for (let j = 0; j < needle.length; j++) {
if (needle[j] !== haystack[i + j]) {
break;
} else if (j === needle.length - 1){
return i;
}
}
}
}
return -1;
};
์ฐ์ ๋์ ํ์ด๋ณด๋ค ๋งค๊ฐ๋ณ์์ ์กฐ๊ฑด์ ๋ํ ์๋ฌ์ผ์ด์ค๋ฅผ ๋ ์์ธํ๊ฒ ์ฒ๋ฆฌํ๋ค.
๊ทธ๋ฆฌ๊ณ ๋์ ๊ฒฝ์ฐ๋ ๋ฉ์๋๋ฅผ ์ผ์ง๋ง ์ด ํ์ด๋ for๋ฌธ๊ณผ if๋ฌธ๋ง์ ์ฌ์ฉํ๋ค.
์๋ฌธ์ ์๋์์ ๋ณผ ์ ์๋ค.
JavaScript solution. No built-in methods. - LeetCode Discuss
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
๐คธโโ๏ธ๐คธโโ๏ธ๐คธโโ๏ธ๐คธโโ๏ธ๐คธโโ๏ธ๐คธโโ๏ธ
๋ฐฉ๋ฌธํด์ฃผ์ ์ ๊ฐ์ฌํฉ๋๋ค! ๐
ํฌ์คํ ๋ค์ ๊ณต๋ถ์ค์ธ ๋ด์ฉ์ ๊ธ๋ก ์์ฑํ ๊ฒ์ด๋ผ ๋ถ์กฑํ ์ ์ด ๋ง์ผ๋ ์ฐธ๊ณ ๋ถํ๋๋ฆฝ๋๋ค.
๋ถ์กฑํ ๋ถ๋ถ์ ๋ํ ์ฝ๋ฉํธ๋ ์ธ์ ๋ ํ์์ ๋๋ค.
์ข์ ํ๋ฃจ ๋์ธ์, ๊ฐ์ฌํฉ๋๋ค! ๐โ
'๐ Algorithm > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] leetCode : Single Number (0) | 2022.05.26 |
---|---|
[JavaScript] leetCode : Reverse Words in a String (0) | 2022.05.16 |
[JavaScript] leetCode : Longest Common Prefix (0) | 2022.05.09 |
[JavaScript] leetCode : Linked List Cycle II (3) | 2022.05.03 |
[JavaScript] leetCode : Valid Mountain Array (3) | 2022.05.02 |
Comment