#50 Longest Common Prefix
๐ฅ Longest Common Prefix ๐ฅ
Example 1:
Input: strs = ["flower", "flow", "flight"];
Output: "fl";
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
์ฝ๋ ์์ฑ
const longestCommonPrefix = function(strs) {
let result;
let prefix = "";
for (let i = 0; i < strs.length; i++) {
result = strs.filter(str => str.slice(i, i + 1) === strs[0][i]);
if (strs.length === result.length) {
prefix += strs[0][i];
} else {
break;
}
}
return prefix === "" ? "" : prefix;
};
๋ ๋ค๋ฅธ ์ ๊ทผ๋ฒ
์ฒซ ๋ฒ์งธ ์์๋ฅผ ๊ธฐ์ค์ด ๋๋ prefix๋ก ์ ํ ๋ค
Str.indexOf()
์ Str.substring()
๋ฉ์๋๋ฅผ ์ฌ์ฉํด์ prefix ๋ฒ์ ์ค์ด๊ธฐ
const longestCommonPrefix = function(strs) {
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
}
}
return prefix;
};
WILT : What I Learned Today ๐ค
- ํจํด์ ๋ฐ๊ฒฌํ์. ๋น๊ต๋ฅผ ํ๋ ค๋ฉด ๊ธฐ์ค์ด ํ์ํ๋ค. ์ฒซ ๋ฐฐ์ด์ด ์์๋ฅผ ๊ธฐ์ค์ผ๋ก ์ ํ๊ณ ๊ฐ์ ๋น๊ตํ๋๊น ๊ฐ๋ ์ฑ๋ ์ข์์ง๊ณ ํจ์ฌ ์ฝ๋๊ฐ ๋จ์ํด์ก๋ค. ์ฒ์๋ถํฐ ์ํ๊ธด ์ด๋ ค์ฐ๋ ์ฐ์ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ณ , ๊ทธ ๋ค์์ ๋ ๋์์ง ๋ฐฉํฅ์ ๋ํด ๊ณ์ ๊ณ ๋ฏผํด๋ณด์. ์ค๋๋ ํ ๋ฌธ์ ๋ฅผ ํ์ด๋๋ค ์์!