확인 알고리즘이 약간 잘못되었습니다. ,
- 는 S1에서 문자를 가져옵니다 인덱스 인 경우 S2
- 내부에 그 문자의 인덱스를 찾습니다
public static void main(String[] args)
{
String s1 = "shotaabb";
String s2 = "hostbaba";
System.out.printf("String s1: %s, String s2: %s%n", s1, s2);
System.out.println(isAnagram(s1, s2) ?
"Is anagram" : "Is not an anagram");
}
static boolean isAnagram(String s1, String s2)
{
String str1 = new String(s1);
String str2 = new String(s2);
// Ensures that both strings are of the same length
if (str1.length() != str2.length())
return false;
int str1Len = str1.length();
for (int i = 0; i < str1Len; i++)
{
int charIndex = str2.indexOf(str1.charAt(i));
if(charIndex == -1) // Not found in str2
return false;
else
{
// Remove the character from str2
str2 = str2.substring(0, charIndex) +
str2.substring(charIndex + 1);
}
}
return true;
}
어떤 코드가하는 것은 :
여기 isAnagram
기능을 편집 -1, s2 안에 문자가 없으면 거짓을 반환합니다.
- s2에서 문자를 찾을 수 있으면 s2에서 문자를 제거하십시오.
(S1) 내부의 모든 문자 (S2)에서 발견 할 수있는 경우 끝에- 는, true를 돌려줍니다 두 문자열은 S1의 모든 문자 (S2)에서 제거 &를 찾을 수 있습니다 경우, 같은 길이의 사실을 바탕으로
- , s1은 s2 &의 아나 그램입니다.
출력 :
String s1: shotaabb, String s2: hostbaba
Is anagram
업데이트 (비교 문자열 배열) : 업데이트 된 코드에 대한
String[] strArr1 = {"shot", "dcba"};
String[] strArr2 = {"host", "abcd"};
for(String s1 : strArr1)
{
for(String s2 : strArr2)
{
System.out.printf("%nString s1: %s, String s2: %s%n", s1, s2);
System.out.println(isAnagram(s1, s2) ?
"Is anagram" : "Is not an anagram");
}
}
출력 :
,536 게일 Laakmann 맥도웰에 의해 저술,이 솔루션은 책에서 가져옵니다
public boolean isAnagram(String s1, String s2) {
class SortChars{
String sort(String source) {
char[] chars = source.toLowerCase().toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}
SortChars sc = new SortChars();
return sc.sort(s1).equals(sc.sort(s2));
}
는 "코딩 인터뷰 균열": 두 문자열 철자 바꾸기 경우
그리고 내 질문에 왜 하향 투표를합니까? 내가 다시 지키지 않도록 내가 지키지 않은 규칙은 무엇인가? – zydexo
그냥 형식화하는 것 같아요? 이유도 모르겠다. – Gosu
음수 값을 얻으려면 Up-voted;). – monnef