[programmers] ad ์ œ๊ฑฐํ•˜๊ธฐ - Java

๋ฌธ์ž์—ด ๋ฐฐ์—ด์—์„œ "ad"๋ฅผ ํฌํ•จํ•˜๋Š” ๋ฌธ์ž์—ด์„ ์ œ๊ฑฐํ•˜๊ณ  ๋‚จ์€ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ์ž๋ฐ” ์†”๋ฃจ์…˜์ž…๋‹ˆ๋‹ค. stream API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์กฐ๊ฑด์— ๋งž์ง€ ์•Š๋Š” ๊ฐ’์„ ํ•„ํ„ฐ๋งํ•˜์—ฌ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
Jan 16, 2024
[programmers] ad ์ œ๊ฑฐํ•˜๊ธฐ - Java

๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ž์—ด ๋ฐฐ์—ด strArr๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ๋ฐฐ์—ด ๋‚ด์˜ ๋ฌธ์ž์—ด ์ค‘ "ad"๋ผ๋Š” ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์„ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” ๋ชจ๋“  ๋ฌธ์ž์—ด์„ ์ œ๊ฑฐํ•˜๊ณ  ๋‚จ์€ ๋ฌธ์ž์—ด์„ ์ˆœ์„œ๋ฅผ ์œ ์ง€ํ•˜์—ฌ ๋ฐฐ์—ด๋กœ return ํ•˜๋Š” solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด ์ฃผ์„ธ์š”.

์ œํ•œ์‚ฌํ•ญ

  • 1 โ‰ค strArr์˜ ๊ธธ์ด โ‰ค 1,000
    • 1 โ‰ค strArr์˜ ์›์†Œ์˜ ๊ธธ์ด โ‰ค 20
    • strArr์˜ ์›์†Œ๋Š” ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ

strArr
result
["and","notad","abcd"]
["and","abcd"]
["there","are","no","a","ds"]
["there","are","no","a","ds"]

์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

์ž…์ถœ๋ ฅ ์˜ˆ #1
  • 1๋ฒˆ ์ธ๋ฑ์Šค์˜ ๋ฌธ์ž์—ด์ธ "notad"๋Š” ๋ถ€๋ถ„ ๋ฌธ์ž์—ด๋กœ "ad"๋ฅผ ๊ฐ€์ง‘๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ํ•ด๋‹น ๋ฌธ์ž์—ด์„ ์ œ๊ฑฐํ•˜๊ณ  ๋‚˜๋จธ์ง€๋Š” ์ˆœ์„œ๋ฅผ ์œ ์ง€ํ•˜์—ฌ ["and","abcd"]๋ฅผ return ํ•ฉ๋‹ˆ๋‹ค.
์ž…์ถœ๋ ฅ ์˜ˆ #2
  • "ad"๊ฐ€ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด๋กœ ๋“ค์–ด๊ฐ„ ๋ฌธ์ž์—ด์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์›๋ž˜ ๋ฐฐ์—ด์„ ๊ทธ๋Œ€๋กœ return ํ•ฉ๋‹ˆ๋‹ค.

solution.java

import java.util.Arrays; class Solution { public String[] solution(String[] strArr) { return Arrays.stream(strArr).filter(item -> !item.contains("ad")).toArray(String[]::new); } }
 

ํ•ต์‹ฌ ํ‚ค์›Œ๋“œ

  • ๋ฐฐ์—ด ๋‚ด์—์„œ stream api๋ฅผ ํ™œ์šฉํ•ด์„œ ํŠน์ • ์กฐ๊ฑด์„ ๊ฐ€์ง„ ๊ฐ’์„ ์ œ๊ฑฐํ•˜์—ฌ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ์ž๋ฐ”์˜ stream์€ Java 8๋ถ€ํ„ฐ ์ง€์›ํ•˜๋Š” ๊ธฐ๋Šฅ์ด๋ฉฐ, ์ปฌ๋ ‰์…˜์— ์ €์žฅ๋˜์–ด์žˆ๋Š” ์—˜๋ฆฌ๋จผํŠธ๋“ค์„ ํ•˜๋‚˜์”ฉ ์ˆœํšŒํ•˜๋ฉด์„œ ์ฒ˜์ดํ•  ์ˆ˜ ์žˆ๋Š” ์ฝ”๋“œํŒจํ„ด์ด๋‹ค.
    • filter๋Š” stream์—์„œ ๋ฝ‘์•„์ ธ ๋‚˜์˜ค๋Š” ๋ฐ์ดํ„ฐ์—์„œ ํŠน์ • ๋ฐ์ดํ„ฐ๋“ค๋งŒ ๊ณจ๋ผ๋‚ผ ์ˆ˜ ์žˆ๋‹ค.
      • filter() ๋ฉ”์†Œ๋“œ์—๋Š” boolean ๊ฐ’์„ ๋ฆฌํ„ดํ•˜๋Š” ๋žŒ๋‹ค์‹์„ ๋„˜๊ฒจ์ฃผ์—ˆ์„ ๋•Œ, ๋žŒ๋‹ค์‹์„ ์ ์šฉํ•ด์„œ true๊ฐ€ ๋ฆฌํ„ด๋˜๋Š” ๋ฐ์ดํ„ฐ๋งŒ ์„ ๋ณ„ํ•˜๋Š” ๊ธฐ๋Šฅ์ด ์žˆ๋‹ค.
  • :: (์ด์ค‘ ์ฝœ๋ก  ์—ฐ์‚ฐ์ž)์˜ ํ˜•ํƒœ๋Š” :: ์•ž์— ์ธ์Šคํ„ด์Šค๊ฐ€ ์˜ค๊ณ , ๋’ค์—๋Š” ๋ฉ”์†Œ๋“œ ๋ช…์ด๋‚˜ new๊ฐ€ ์˜ค๋ฉด ๋œ๋‹ค.
 

๊ฒฐ๋ก !

ํ•ด๋‹น ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด์„œ stream์˜ ํ™œ์šฉ๋ฒ•์„ ์ตํž ์ˆ˜ ์žˆ์—ˆ๋‹ค.
 
Share article

More articles

See more posts

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ปDriedPollack's Blog