첫 번째 문자열에있는 두 번째 문자열에서 문자를 제거하는 프로그램을 작성했습니다. 복잡성은 BigO (n^2)가됩니다. 복잡성을 더 줄일 수 있습니까?첫 번째 문자열에있는 두 번째 문자열에서 문자 제거
public class Tmp {
public static void main(String[] args) {
String s = "halloween";
String s1 = "halcyon";
char[] ss = s.toCharArray();
char[] ss1 = s1.toCharArray();
for(int i=0;i<ss.length;i++){
for(int j=0;j<ss1.length;j++){
if(ss1[j] == ss[i]){
ss1[j] = 'x'; //Replace the common char with x
}
}
}
System.out.println(Arrays.toString(ss1));
}
}
OUTPUT
[x, x, x, c, y, x, x]
더 나은 결과를 위해 코드 검토에 코드를 추가 할 수 있습니다. http://codereview.stackexchange.com/ –
예, 'O (n log n)'으로 줄일 수 있습니다. –
string1의 모든 문자를 집합 ('O (n)')에 추가하십시오. 다음으로, string-2의 각 char에 대해 set-1에서'contains()'를 사용하고 char가 있으면 'x'로 설정하십시오. ('O (n)') – TheLostMind