> Java > java지도 시간 > 본문

Java의 철자 바꾸기 프로그램

PHPz
풀어 주다: 2024-08-30 16:26:59
원래의
635명이 탐색했습니다.

철자 바꾸기는 다른 단어의 글자를 다시 섞거나 재배열하여 형성된 단어입니다. 철자 바꾸기의 핵심은 문자가 한 번만 사용될 수 있고 새 단어에서 반복되어서는 안 된다는 것입니다. 철자 바꾸기(Anagram)는 같은 수의 문자로 구성된 단어입니다. 여기서 카운트는 매우 중요합니다. Java의 Anagram 프로그램은 두 문자열을 정렬하고 비교하여 위의 방법으로 사용할 수 있습니다. 이것이 성공하면 문자열이 철자 바꾸기임을 의미합니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

알고리즘:

특정 단어에서 철자 바꾸기 알고리즘을 살펴보겠습니다. 철자 바꾸기를 알아내는 방법에는 세 가지가 있습니다. 세 가지 방법을 하나씩 설명하겠습니다. 기본 알고리즘은 문자열의 길이를 확인하는 것으로 구성됩니다. 길이가 동일하면 정렬하거나 계산하여 철자법을 확인할 수 있습니다.

Java의 Anagram 프로그램 예

주어진 문자열에 대해 가장 먼저 할 수 있는 일은 철자법인지 확인해야 하는 두 문자열을 모두 정렬하는 것입니다. 정렬이 완료되면 정렬된 순서대로 비교할 수 있습니다. 이 방법의 시간 복잡도는 O(n Logn)입니다. 이에 대한 Java 코드는 다음과 같이 작성할 수 있습니다.

예시 #1

코드:

// JAVA program to validate if two strings are anagrams
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
class Main {
/* Below is a function which checks if the strings are anagram */
static boolean checkAnagram(char[] strana1, char[] strana2)
{
// Finding lengths of strings
int len1 = strana1.length;
int len2 = strana2.length;
// If lengths do not match then they cannot be anagrams
if (len1 != len2)
return false;
// Sort both strings
Arrays.sort(strana1);
Arrays.sort(strana2);
// Comparing the strings which are sorted earlier
for (int i = 0; i < len1; i++)
if (strana1[i] != strana2[i])
return false;
return true;
}
/* Main program to test Anagram*/
public static void main (String args[])
{
char strana1[] = { 't', 'e', 's', 't' };
char strana2[] = { 't', 't', 'e', 'w' };
if (checkAnagram(strana1, strana2))
System.out.println("The strings to be checked are" + " anagram of each other");
else
System.out.println("The strings to be checked are not" + " anagram of each other");
}
}
로그인 후 복사

위 프로그램은 먼저 주어진 두 문자열의 길이를 확인합니다. 문자열의 길이가 동일하지 않으면 false를 반환합니다. 두 문자열의 길이가 동일한 경우에만 프로그램이 더 진행됩니다. 배열 정렬 기능을 사용하면 문자열을 두 개의 배열로 정렬합니다. 배열 정렬 기능이 두 문자열 모두에 사용되면 문자열이 비교되고 루프에서 각 문자가 비교됩니다. for 루프가 성공하고 두 문자열의 모든 문자가 동일하면 출력은 철자 바꾸기입니다. 문자 하나가 일치하지 않더라도 false를 반환합니다. 여기서 메인 프로그램은 문자열을 확인하고 checkAnagram 함수에서 반환된 결과에 따라 문자열이 철자법인지 아닌지를 표시합니다.

출력:

Java의 철자 바꾸기 프로그램

w 대신 't', 't', 'e', ​​'s'로 입력을 변경하면 출력은 아래와 같습니다.

출력:

Java의 철자 바꾸기 프로그램

예시 #2

이 방법은 검증 대상 문자열이 작을 때 사용할 수 있습니다. 이 방법에서는 저장된 문자가 8비트이고 최대 256자를 저장할 수 있다고 간주합니다. 이 방법에서는 먼저 크기가 256인 카운트 배열을 사용하여 문자열을 계산하고 카운트 배열에서 필요한 모든 값을 0으로 초기화할 수 있습니다. 이 배열을 순회하고 순회하는 동안 개수를 증가시킵니다. 이 작업이 완료되면 개수 배열을 비교할 수 있습니다. 개수가 동일하면 반환된 결과는 true입니다.

코드:

import java.io.*;
import java.util.*;
class ANA {
static int NO_CHARS = 256;
/* Below is a function which checks if the strings are anagram */
static boolean isAnagram(char strana1[], char strana2[])
{
// Here we create two arrays and initialize it to 0
int cnt1[] = new int[NO_CHARS];
Arrays.fill(cnt1, 0);
int cnt2[] = new int[NO_CHARS];
Arrays.fill(cnt2, 0);
int i;
// For every character in input strings, increment the count
for (i = 0; i < strana1.length && i < strana2.length;
i++) {
cnt1[strana1[i]]++;
cnt2[strana2[i]]++;
}
// Checking If both strings are of different length
if (strana1.length != strana2.length)
return false;
// Compare count arrays
for (i = 0; i < NO_CHARS; i++)
if (cnt1[i] != cnt2[i])
return false;
return true;
}
/* Main program to test to check if string is Anagram or not*/
public static void main(String args[])
{
char strana1[] = ("silent").toCharArray();
char strana2[] = ("lisent").toCharArray();
if (isAnagram(strana1, strana2))
System.out.println("The strings to be checked are" + " anagram of each other");
else
System.out.println("The strings to be checked are not" + " anagram of each other");
}
}
로그인 후 복사

출력:

Java의 철자 바꾸기 프로그램

예시 #3

Java의 StringBuilder 함수를 사용하여 철자법을 확인할 수 있습니다. 두 번째 문자열에 있는 모든 문자를 삭제하려면 deletechartAt() 메소드를 사용할 수 있습니다.

코드:

public class Main
{
static void findAnagram(String str1, String str2)
{
String copystr1 = str1.replaceAll( " ", "").toLowerCase();
String copystr2 = str2.replaceAll(" ", "").toLowerCase();
//Setting the initial status to true
boolean flag = true;
if(copystr1.length() != copystr2.length())
{
//If copystr1 and copystr2 do not have same length then set the flag to false
flag = false;
}
else
{
//changing copystr1 to char array
char[] str1Array = copystr1.toCharArray();
//Creating StringBuilder from copystr2
StringBuilder sb = new StringBuilder(copystr2);
//Validating if  each character of str1Array is present in string builder
for (char c : str1Array)
{
int index = sb.indexOf(""+c);
if (index != -1)
{
sb = sb.deleteCharAt(index);
}
else
{
//If each character is not present, setting flag to false and breaking the loop
flag = false;
break;
}
}
}
if(flag)
{
System.out.println(str1+" and "+str2+" are anagrams");
}
else
{
System.out.println(str1+" and "+str2+" are not anagrams");
}
}
public static void main(String[] args)
{
findAnagram("Silent", "Listen");
}
}
로그인 후 복사

여기서 프로그램은 플래그를 사용하고 추가 문자를 삭제하는 데 도움이 되는 문자열 작성 모듈을 사용합니다.

출력:

Java의 철자 바꾸기 프로그램

위 내용은 Java의 철자 바꾸기 프로그램의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!