본문 바로가기

코딩테스트/Coding Bat

[코딩뱃] [자바] Warmup - 1단계 : missingChar 문제

728x90
728x90

https://codingbat.com/prob/p190570

 

CodingBat Java Warmup-1 missingChar

Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..str.length()-1 inclusive).missingChar("kitten", 1)

codingbat.com



= 문제 번역 =

비어 있지 않은 문자열과 int n이 주어지면 인덱스 n에 위치한 char을 제거한 후의 새로운 문자열을 반환합니다. 

n 값은 원래 문자열에 있는 char의 유효한 인덱스가 됩니다(즉, n은 0..str.length()-1 포함).

 

= 문제푸는 팁 =

단순하게 remove들로 삭제하는 것이아닌, n위치에 입력한 문자를 삭제하고, n+1에 위치한 문자가 n의 위치로 당겨져야한다는 부분을

확인하면서 문제풀기!

 

= 해설 =

< 1 >
public String missingChar(String str, int n) {
int len = str.length();
  String firsthalf = str.substring(0, n);
 
  String secondhalf = str.substring(n+1, len);
  
  return firsthalf + secondhalf ;
}

< 2 >
public String missingChar(String str, int n) {
  String front = str.substring(0, n);
  
  // Start this substring at n+1 to omit the char.
  // Can also be shortened to just str.substring(n+1)
  // which goes through the end of the string.
  String back = str.substring(n+1, str.length());
  
  return front + back;
}

728x90