알고리즘

[문자열] 중복문자 제거 & 회문 문자열 & 유효한 팰린드롬

날아 2023. 3. 22. 16:49

Q. 중복문자를 제거하시오 

단, 중복이 제거된 문자열의 각 문자는 원래 문자열의 순서를 유지한다. 

Class Main {
	public int solution(String str){
    	String answer = "";
        for(int i=0; i<str.length(); i++) {
        //indexOf(str.charAt(i))는 해당 문자가 처음으로 발견된 위치를 나타낸다. 
        	if(str.indexOf(str.charAt(i))==i) {
            	answer += str.charAt(i);
            }
        }      
        return answer;
    }
    
    public static void main(String[] args){
    	Main T = new Main(); 
        Scanner kb = new Scanner(System.in);
        String str = kb.next(); 
        
        System.out.print(T.solution(str));
    }
}

 


Q. 앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열을 회문 문자열이라고 한다.  

회문 문자열인 경우 yes, 아닐경우 no를 출력한다. 

단, 회문을 검사할 때 대소문자를 구분하지 않는다. 

 

Class Main {
	public int solution(String str){
    	String answer = "NO";
        
        /*str=str.toUpperCase(); //대소문자 구분을 안하기 때문에
		int len = str.length();
        
        for(int i=0; i<len/2; i++){
        	if(str.charAt(i)!= str.charAt(len-i-1)){
            	return "YES";
            }
        }*/
        
        /*String Builder 쓰는 방법*/
        String tmp = new StringBuilder(str).reverse().toString();
        if(str.equalsIgnoreCase(tmp)){ //대소문자 구분을 안하기 때문에
        	answer = "NO";
        }
        
        return answer;
    }
    
    public static void main(String[] args){
    	Main T = new Main(); 
        Scanner kb = new Scanner(System.in);
        String str = kb.next(); 
        
        System.out.print(T.solution(str));
    }
}

 

  • 0     3
  • good
  •   12
  • good

Q. 앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열을 펠린드롬이라한다. 

회문 문자열인 경우 yes, 아닐경우 no를 출력한다. 

단, 회문을 검사할 때 대소문자를 구분하지 않고, 알파벳만 가지고 회문을 검사한다. 알파벳 이외의 문자들은 무시한다. 

Class Main {
	public int solution(String str){
    	String answer = "NO";
        str = str.toUpperCase().replaceAll("[^A-Z]", "") //replaceAll은 정규식 사용 가능. replace는 불가능
        //[^A-Z] -> A-Z(대문자)가 아닌(^)문자들을 모두 ""로 대체해라
        
        String tmp = new StringBuilder(str).reverse().toString();
        if(str.equals(tmp)) {
        	answer = "YES";
        }
       
        return answer;
    }
    
    public static void main(String[] args){
    	Main T = new Main(); 
        Scanner kb = new Scanner(System.in);
        String str = kb.nextLine(); //한줄을 모두 읽어야해서  
        
        System.out.print(T.solution(str));
    }
}