Leetcode Algorithm No.1170 - Compare Strings by Frequency of the Smallest Character

가장 작은 문자의 반복 횟수로 문자열 비교하기

Duckuism
Duckuism
Published in
4 min readJan 11, 2020

--

기능별로 함수를 나누어서 구현하는 것이 명확하게 로직을 볼 수 있음.
자바의 문자열 관련 함수, 형변환 방법을 정리해야겠다는 생각을 하게 됨.
문제를 풀면서 계속 추가하고 정리해야 할 듯.

//Java
class Solution {
public int[] numSmallerByFrequency(String[] queries, String[] words) {
int[] result = new int[queries.length];

for( int i = 0; i<queries.length; i++){
int cnt = 0;
for( String w : words){
if(calculateFrequencyOfMinValue(queries[i])<calculateFrequencyOfMinValue(w)){
cnt += 1;
}
}
result[i] = cnt;
}
return result;
}

public int calculateFrequencyOfMinValue(String str){
byte[] ascii = stringToBytesASCII(str);
int minValue = getMin(ascii);
int cnt = 0;
for ( byte e : ascii){
if(e == minValue){
cnt += 1;
}
}
return cnt;
}

public int getMin(byte[] b){
int minValue = b[0];
for(int i = 0; i<b.length; i++){
if(b[i] <= minValue){
minValue = b[i];
}
}
return minValue;
}

public static byte[] stringToBytesASCII(String str){
byte[] b = new byte[str.length()];
for(int i = 0; i<b.length; i++){
b[i] = (byte) str.charAt(i);
}
return b;
}
}
//JavaScript ES6
/**
* @param {string[]} queries
* @param {string[]} words
* @return {number[]}
*/
var numSmallerByFrequency = function(queries, words) {
let result = [];
queries.map(e => {
let cnt = 0;
let minValue = getMin(e);
let duplicatedCntQ = duplicatedCnt(minValue, e);
words.map(w => {
let minValue = getMin(w);
let duplicatedCntW = duplicatedCnt(minValue, w);
if(duplicatedCntQ < duplicatedCntW){
cnt+=1;
}
})
result.push(cnt);
})
return result;
};
const getMin = (str) => {
let minValue = str[0];
for(let i=0; i<str.length; i++){
if(minValue >= str[i]){
minValue = str[i];
}
}
return minValue;
}
const duplicatedCnt = (minValue, str) =>{
let cnt = 0;
for(let i = 0; i<str.length; i++){
if(minValue === str[i]){
cnt+=1;
}
}
return cnt;
}

--

--