class Solution {
public int solution(String s) {
int answer = 0;
int count1 = 0;
int count2 = 0;
char a = s.charAt(0);
for (int i = 0; i < s.length(); i++) {
if(a == s.charAt(i)) {
count1++;
}
else {
count2++;
}
if(count1 == count2) {
answer++;
count1 = 0;
count2 = 0;
if(i+1 < s.length()) {
a = s.charAt(i+1);
}
}
else if(count1 != count2 && i+1 == s.length()) {
answer++;
}
}
return answer;
}
}
입출력 예시를 보면서 하나하나 조건을 맞춰가다보니 풀 수 있었다.
@Slf4j(topic = "UseTimeAop")
@Aspect
@Component
@RequiredArgsConstructor
public class UseTimeAop {
private final ApiUseTimeRepository apiUseTimeRepository;
@Pointcut("execution(* com.sparta.newsfeed.controller.CommentController.*(..))")
private void comment() {}
@Pointcut("execution(* com.sparta.newsfeed.controller.ProductController.*(..))")
private void product() {}
@Pointcut("execution(* com.sparta.newsfeed.controller.UserController.*(..))")
private void user() {}
@Pointcut("execution(* com.sparta.newsfeed.controller.WishController.*(..))")
private void wish() {}
@Around("comment() || product() || user() || wish()")
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable{
long startTime = System.currentTimeMillis();
try {
//핵심 기능 수행
Object output = joinPoint.proceed();
return output;
} finally {
long endTime = System.currentTimeMillis();
long runTime = endTime - startTime;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth != null && auth.getPrincipal().getClass() == UserDetailsImpl.class) {
UserDetailsImpl userDetails = (UserDetailsImpl) auth.getPrincipal();
User loginUser = userDetails.getUser();
ApiUseTime apiUseTime = apiUseTimeRepository.findByUser(loginUser).orElse(null);
if (apiUseTime == null) {
apiUseTime = new ApiUseTime(loginUser, runTime);
} else {
apiUseTime.addUseTime(runTime);
}
log.info("Username: " + loginUser.getNickname() + ", Total Time: " + apiUseTime.getTotalTime());
apiUseTimeRepository.save(apiUseTime);
}
}
}
}
@Around("comment() || product() || user() || wish()")를 통해 각 컨트롤러의 핵심 기능을 수행하기 전과 후에 부가 기능(runtime 시간 측정)이 실행될 수 있도록 설정하였다.
@Pointcut을 통해 각 컨트롤러의 메서드를 설정할 수 있었다.