๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

[Algorithm] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.1 : ์„œ์šธ์—์„œ ๊น€์„œ๋ฐฉ ์ฐพ๊ธฐ

by ์ฝ”๋”ฉ๊ณต์ฑ… 2022. 11. 5.
๋ฐ˜์‘ํ˜•

์„œ์šธ์—์„œ ๊น€์„œ๋ฐฉ ์ฐพ๊ธฐ

Stringํ˜• ๋ฐฐ์—ด seoul์˜ element์ค‘ "Kim"์˜ ์œ„์น˜ x๋ฅผ ์ฐพ์•„, "๊น€์„œ๋ฐฉ์€ x์— ์žˆ๋‹ค"๋Š” String์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•˜์„ธ์š”. seoul์— "Kim"์€ ์˜ค์ง ํ•œ ๋ฒˆ๋งŒ ๋‚˜ํƒ€๋‚˜๋ฉฐ ์ž˜๋ชป๋œ ๊ฐ’์ด ์ž…๋ ฅ๋˜๋Š” ๊ฒฝ์šฐ๋Š” ์—†์Šต๋‹ˆ๋‹ค.


์ œํ•œ ์กฐ๊ฑด

- seoul์€ ๊ธธ์ด 1 ์ด์ƒ, 1000 ์ดํ•˜์ธ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
- seoul์˜ ์›์†Œ๋Š” ๊ธธ์ด 1 ์ด์ƒ, 20 ์ดํ•˜์ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค.
- "Kim"์€ ๋ฐ˜๋“œ์‹œ seoul ์•ˆ์— ํฌํ•จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.


์ž…์ถœ๋ ฅ ์˜ˆ

seoul return
["Jane", "Kim"] "๊น€์„œ๋ฐฉ์€ 1์— ์žˆ๋‹ค"

๋ฌธ์ œ ํ’€์ด

์ƒ์ˆ˜ seoul์—๋Š” ["Jane", "Kim"] ๋‘ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ ๊ฐ’์ด ๋“ค์–ด๊ฐ€ ์žˆ์œผ๋ฉฐ ์ด ์ค‘ 1๋ฒˆ์งธ ๋ฐ์ดํ„ฐ ๊ฐ’์€ "Kim"์ด๋‹ค. seoul.indexOf('Kim')์„ ์“ด๋‹ค๋ฉด ๋‚˜์˜ค๋Š” ๊ฐ’์€ '1'์ด๋ฉฐ, ์ตœ์ข…์ ์œผ๋กœ ๋ณ€์ˆ˜ answer์—๋Š” ใ€Œ๊น€์„œ๋ฐฉ์€ 1์— ์žˆ๋‹คใ€๊ฐ€ ์ €์žฅ๋˜๋ฉฐ return answer๋ฅผ ํ†ตํ•ด ํ•ด๋‹น ๊ฐ’(๋ฌธ์žฅ)์ด ๋ฐ˜ํ™˜๋œ๋‹ค.

function solution(seoul) {
    var answer = "๊น€์„œ๋ฐฉ์€ " + seoul.indexOf('Kim') + "์— ์žˆ๋‹ค";
    return answer;
}

๋‹ค๋ฅธ ํ’€์ด ๋ฐฉ์‹

์ถœ์ฒ˜ : ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์Šค์ฟจ

for๋ฌธ์„ ํ†ตํ•ด seoul[i]๊ฐ€ "Kim"์ผ ๋•Œ answer์— "๊น€์„œ๋ฐฉ์€ "+to_string(i)+"์— ์žˆ๋‹ค"๋ฅผ ์ €์žฅ์‹œํ‚จ๋‹ค. to_string(i)๋Š” vector<string> seoul๋ฅผ ํ†ตํ•ด seoul์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ๋“ค์–ด๊ฐ€๊ฒŒ ๋˜๊ณ  ์ฆ‰ to_string(i)๋Š” 1์„ ์˜๋ฏธํ•˜๊ฒŒ ๋˜๋ฉฐ ์ตœ์ข…์ ์œผ๋กœ ใ€Œ๊น€์„œ๋ฐฉ์€ 1์— ์žˆ๋‹คใ€๊ฐ€ ์ถœ๋ ฅ๋œ๋‹ค.

#include <string>
#include <vector>

using namespace std;

string solution(vector<string> seoul) {
    string answer = "";
    for(int i=0;i<seoul.size();i++){
        if(seoul[i]=="Kim")
            answer="๊น€์„œ๋ฐฉ์€ "+to_string(i)+"์— ์žˆ๋‹ค";
    }
    return answer;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€


Reference Book

JavaScript
HTML
CSS
๊ด‘๊ณ  ์ค€๋น„์ค‘์ž…๋‹ˆ๋‹ค.