본문 바로가기

데일리

알고리즘연습: 특수문자제외한 문자 뒤집기

public class Main2 {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
//		String str = s.nextLine();
		// 스캐너로 콘솔입력 귀챦. 테스트시 변수에 담아서 돌리는게 더 편리
		String str = "a#b!GE*T@S";
		
		System.out.println(solution(str));

		
	}//end main

	private static String solution(String str) {
		String answer = "";
		
		//0.리스트에 할당
		List<String> list = Arrays.asList(str.split(""));
		System.out.println(list);
		
		//1-1.스트림 필터로(charAt 이용) 알파벳만 뽑아서 반환: 타입 String
		String temp = list.stream()
				.filter(x->Character.isAlphabetic(x.charAt(0)))
				.collect(Collectors.joining());
		System.out.println("1 temp: " + temp);
		
		//1-2.스트림 필터로(matches 이용) 알파벳만 뽑아서 반환: 타입 String
//		String temp = list.stream()
//				.filter(x->x.matches("[a-zA-Z]"))
//				.collect(Collectors.joining());
//		System.out.println(temp);
		
		//3.temp 뒤집기
		String reverseStr = new StringBuffer(temp).reverse().toString();
		System.out.println(reverseStr);
		
		//4.뒤집은 문자열을 Stack에 추가
		Stack<String> stack = new Stack<String>();
		for (String x : reverseStr.split("")) {
			stack.push(x);
		}
		
		// stack :
//		pop(): 맨 나중에 것을 제거 및 반환
//		remove(0): 0번방 것을 제거 및 반환
		
		//5.알파벳인 것들만 스텍에서 뽑아서 변경
		for (int i = 0; i < list.size(); i++) {
//			System.out.println(list.get(i).matches("[a-zA-Z]"));
			if(list.get(i).matches("[a-zA-Z]")) {
				list.set(i, stack.remove(0)); //리스트add넣고 get추출 set변경
				//리스트에 문자가있을 인덱스위치에 스택에서 호출한(스택0번째부터) 문자를 기입
			}
		}
		System.out.println("list :: "+list);
		
		//6.문자열로 변환해서 할당
//		answer = String.join("", list);
//		answer = list.stream().collect(Collectors.joining());
		answer = list.stream().reduce("", String::concat);
		return answer;
	}

}//end class

 

 

굳이 이렇게 푸나 싶었지만.. 다양한 방법예시를 위함이라 생각하고 기록남긴다

 

입력:a#b!GE*T@S

출력:

S#T!EG*b@a