반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

지난 번에 Leetcode의 Anagram 문제를 한번 풀어 봤는데요.

이번에 Technical Interview 보면서 이 Anagram 문제가 나와서 한번 풀어봤습니다.

 

지난번 했던 방법으로 풀었기 했는데... 나중에 생각해 보니 또 다른 방법이 생각 나더라고요.

일단 지난번 글은 아래 링크에 있습니다.

 

https://coronasdk.tistory.com/1156

 

Leetcode - 242. Valid Anagram : Easy

오늘의 문제는 이것입니다. 2개의 Strings가 input이고 그 두개의 문자열이 같은 문자들을 포함하고 있으면 (순서는 바뀌어도 됨) true 이고 아니면 false 입니다. 먼저 Pattern을 찾아 보겠습니다. 1. 두

coronasdk.tistory.com

 

이 때 사용했던 로직을 풀면 아래와 같이 할 수 있습니다.

 

class Anagram1 {

    public static void main(String[] args) {

        boolean result = true;

        String s = "abcd";

        String t = "cdab";

        

        if(s.length() != t.length()) {

            result = false;

        }

        

        int[] sCounter = new int[26];

        int[] tCounter = new int[26];

        

        for(int i=0; i<s.length(); i++) {

            sCounter[s.charAt(i) - 'a']++;

            tCounter[t.charAt(i) - 'a']++;

        }

        

        for(int i = 0; i<26; i++){

            if(sCounter[i] != tCounter[i]){

                result = false;

            }

        }

        

        if(result) {

            System.out.println("This is Anagram.");

        } else {

            System.out.println("This is not Anagram");

        }

    }

}

 

ASCII Code를 이용한 방법인데요.

자세히 보시려면 위에 있는 링크로 가시면 설명한 것을 보실 수 있습니다.

 

이번엔 ArrayList로 루프 없이 만든 코드 입니다.

 

import java.io.*; 

import java.util.*; 

 

class Anagram2 {

    public static void main(String[] args) {

        boolean result = true;

        String s = "abcd";

        String t = "cdab";

        

        if(s.length() != t.length()) {

            result = false;

        }

        

        String[] sSplit = s.split("");

        String[] tSplit = t.split("");

  

        ArrayList<String> sList = new ArrayList<String>(

            Arrays.asList(sSplit));

        ArrayList<String> tList = new ArrayList<String>(

            Arrays.asList(tSplit));

        

        Collections.sort(sList);

        Collections.sort(tList);

        

        result = sList.equals(tList);

        

        if(result) {

            System.out.println("This is Anagram.");

        } else {

            System.out.println("This is not Anagram");

        }

    }

}

 

String 을 ArrayList로 만들어서 sorting을 하고 equals()를 사용해서 문제를 풀었습니다.

 

근데 역시 ASCII를 이용해서 for loop를 돌리는데 Runtime 이나 Memory 관리 면에서 훨씬 더 나은 방법인데요.

 

반응형