简体   繁体   English

将字符串中的字符按字母顺序排序,没有数组或映射(Java)

[英]Sorting characters in a string into alphabetical order without arrays or maps (Java)

I am trying to make a program which tests if two separate phrases are anagrams of each other. 我正在尝试制作一个程序,用于测试两个单独的词组是否是彼此的字谜。 To do this, I want to sort each string phrase into alphabetical order and compare the results. 为此,我想将每个字符串短语按字母顺序排序并比较结果。 However, I want to do this without using any arrays or maps . 但是, 我想这样做而不使用任何数组或映射 So far I have some pretty messy code/pseudocode: 到目前为止,我有一些非常凌乱的代码/伪代码:

import java.util.Scanner;

public class AnagramComparer{
  public static void main(String[] args){
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a sentence.");

    String sentence = scan.nextLine();    

    sentence = sentence.toLowerCase();

    String empty1 = "";

    for(int i = 0; i <= sentence.length(); i++){

      //if char is between 97 & 122

      // if char i <= charAt (0 to sentence length - x)               

      if(sentence.charAt(i) <= empty1.charAt(0)){
        empty1.replace(empty1.charAt(0), sentence.charAt(i));                   
      }
      else{ 
        empty1 = (empty1 + (sentence.charAt(i)));
      }
    } 
    System.out.println(empty1);
    System.out.println(sentence);
  }
}

The idea here is that I would run through the string sentence character-by-character and sort it alphabetically in the string empty1. 这里的想法是,我将逐个字符处理字符串句子,并将其按字母顺序在字符串empty1中排序。 Feel free to tell me if I'm going in the wrong direction; 随时告诉我我走错了方向。 any help would be much appreciated. 任何帮助将非常感激。

Strings are immutable, so empty1.replace returns the new string, it doesn't modify the existing one. 字符串是不可变的,因此empty1.replace 返回新字符串,它不会修改现有字符串。

Since String uses a char[] internally, a new String means a new char[] , so you're still using arrays . 由于String使用char[]内,一个新的String意味着新char[]所以你还在使用数组 You might as well use your own char[] for better performance and lower memory footprint. 您也可以使用自己的char[]获得更好的性能并减少内存占用。

char[] chars = sentence.toLowerCase().toCharArray();
Arrays.sort(chars);

Well, arranging characters in a string into alphabetical order is a good idea, but it could be better to make a string like: String alph = "abcdefghijklmnopqrstuvwxyz" and check that the count of every character in alph in both strings are the same. 好的,将字符串中的字符按字母顺序排列是一个好主意,但最好使字符串类似: String alph = "abcdefghijklmnopqrstuvwxyz"并检查两个字符串中alph中每个字符的计数是否相同。

Something like: 就像是:

String alph = "abcdefghijklmnopqrstuvwxyz"
for (int i = 0; i < alph.length(); i++){
    if (StringUtils.countMatches(string1, alph.charAt(i) != StringUtils.countMatches(string2, alph.charAt(i)){
        // not an anagram
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM