Computer/Algorithm

Daily Algorithm - commonCharacterCount

kentakang 2018. 2. 17. 19:44
반응형

Given two strings, find the number of common characters between them.

Example

For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.

Strings have 3 common characters - 2 "a"s and 1 "c".

Input/Output

  • [execution time limit] 3 seconds (java)

  • [input] string s1

    A string consisting of lowercase latin letters a-z.

    Guaranteed constraints:
    1 ≤ s1.length ≤ 15.

  • [input] string s2

    A string consisting of lowercase latin letters a-z.

    Guaranteed constraints:
    1 ≤ s2.length ≤ 15.

  • [output] integer

풀이

public class CommonCharacterCount {
static int commonCharacterCount(String s1, String s2) {
int[] a = new int[26];
int[] b = new int[26];
int sum = 0;

for (int i = 0; i < s1.length(); i++) {
a[(int) s1.charAt(i) - 97]++;
}

for (int i = 0; i < s2.length(); i++) {
b[(int) s2.charAt(i) - 97]++;
}

for (int i = 0; i < a.length; i++) {
if (a[i] != 0 && b[i] != 0) {
if (a[i] <= b[i])
sum += a[i];
else if (b[i] < a[i])
sum += b[i];
}
}

return sum;
}

public static void main(String[] args) {
String s1 = "abca";
String s2 = "xyzabc";

System.out.println(commonCharacterCount(s1, s2));
}
}

문제 출처 : https://codefights.com/arcade/intro/level-3/JKKuHJknZNj4YGL32/



반응형