์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜1] ์ค‘๋ณต๋ฌธ์ž์ œ๊ฑฐ (Javascript)

์€์ง„ 2021. 6. 25. 10:51

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜1] ์ค‘๋ณต๋ฌธ์ž์ œ๊ฑฐ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-25

1. str.indexOf(s, begin)

  • ์ฐพ์œผ๋ ค๋Š” ๋ฌธ์ž์—ด๊ณผ ์ผ์น˜ํ•˜๋Š” ์ฒซ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜
  • begin : ์ฐพ๊ธฐ ์‹œ์ž‘ํ•˜๋Š” ์œ„์น˜, ๊ธฐ๋ณธ๊ฐ’ 0
  • begin์ด ์Œ์ˆ˜์ธ ๊ฒฝ์šฐ, ์ „์ฒด ๋ฌธ์ž์—ด ํƒ์ƒ‰
  • begin์ด str.length๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ๊ฒฝ์šฐ, -1 ๋ฐ˜ํ™˜
  • ์ผ์น˜ํ•˜๋Š” ๊ฐ’์ด ์—†๋Š” ๊ฒฝ์šฐ -1 ๋ฐ˜ํ™˜
  • ๋Œ€์†Œ๋ฌธ์ž ๊ตฌ๋ถ„
  • ๋‘๋ฒˆ์งธ ๋“ฑ์žฅ ์ธ๋ฑ์Šค ๊ตฌํ•˜๊ธฐ : ์ฒซ๋ฒˆ์งธ ๋“ฑ์žฅ ์ธ๋ฑ์Šค + 1
const str = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const index = str.indexOf('dog');

console.log(index);  // output (์ฒซ๋ฒˆ์งธ ๋“ฑ์žฅ ์ธ๋ฑ์Šค): "40"

console.log(str.indexOf('dog', index + 1));  // output (๋‘๋ฒˆ์งธ ๋“ฑ์žฅ ์ธ๋ฑ์Šค): "52"
  • ์กด์žฌ์—ฌ๋ถ€ ํ™•์ธํ•˜๊ธฐ : return์ด -1 ์•„๋‹Œ์ง€ ํ™•์ธ
'Blue Whale'.indexOf('Blue') !== -1; // true, ์กด์žฌ
'Blue Whale'.indexOf('Bloe') !== -1; // false, ์กด์žฌx

2. str.lastIndexOf(s, begin)

  • ์ฐพ์œผ๋ ค๋Š” ๋ฌธ์ž์—ด๊ณผ ์ผ์น˜ํ•˜๋Š” ์ธ๋ฑ์Šค๋ฅผ ์—ญ์ˆœ์œผ๋กœ ํƒ์ƒ‰ํ•˜์—ฌ ๋ฐ˜ํ™˜
  • begin : ์ฐพ๊ธฐ ์‹œ์ž‘ํ•˜๋Š” ์œ„์น˜
  • begin์ด ์Œ์ˆ˜์ธ ๊ฒฝ์šฐ, 0๋ฒˆ์งธ ์ธ๋ฑ์Šค๋งŒ ํƒ์ƒ‰ (0๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์—ญ์ˆœ์œผ๋กœ ํƒ์ƒ‰)
  • begin์ด str.length๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ๊ฒฝ์šฐ, ์ „์ฒด ๋ฌธ์ž์—ด ํƒ์ƒ‰
  • ์ผ์น˜ํ•˜๋Š” ๋ฌธ์ž์—ด์ด ์—†์œผ๋ฉด -1 ๋ฐ˜ํ™˜
const str = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';

console.log(str.lastIndexOf('dog'));  // output: "52"

3. str์˜ ์›์†Œ s์˜ ์ธ๋ฑ์Šค === str.indexOf(s) ์ธ ๊ฒฝ์šฐ ์ถœ๋ ฅ


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-25

function solution(str) {
  let res = '';
  for (let i=0; i<str.length; i++) {
    if (i === str.indexOf(str[i])) res += str[i];
  }
  return res;
}