如何重新编码代码只使用循环和简单数组?

时间:2018-01-31 13:27:38

标签: java arrays loops anagram

我写了那段代码并且它正在运行。但我需要重构它。我只能使用简单的方法来解决问题,例如:“for”循环和简单数组。

public class Anagram {

public static void main(String[] args) throws IOException {

    Anagram anagrama = new Anagram();

   try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));) {

        System.out.println("Enter word or phrase: ");
        String userText = reader.readLine();
        String resultAnagrama = anagrama.makeAnagram(userText);
        System.out.println("Result of Anagrama : " + resultAnagrama);                   
   }      
}

此方法接受用户的文字并制作字谜,但所有非字母应保留在相同的位置

/**
 * @param text
 * @return reversed text and all non-letter symbols stay on the same places
 */
public String makeAnagram(String text) {

    HashMap<Integer, Character> mapNonLetters;

    String[] textFragments = text.split(" ");
    StringBuilder stringBuilder = new StringBuilder();

    //Check each elements of array for availability symbols and make reverse of elements
    for (int i = 0; i < textFragments.length; i++) {
        char[] arrayCharacters = textFragments[i].toCharArray();
        mapNonLetters = saerchNonLetters(arrayCharacters); // search symbols

        StringBuilder builderAnagramString = new StringBuilder(textFragments[i]);

        //Delete all non-letters from element of array
        int reindexing = 0;
        for (HashMap.Entry<Integer, Character> entry : mapNonLetters.entrySet()) {
            int key = entry.getKey();
            builderAnagramString.deleteCharAt(key - reindexing);
            reindexing ++;
        }

        builderAnagramString.reverse();

        //Insert all non-letters in the same places where ones stood
        for (HashMap.Entry<Integer, Character> entry : mapNonLetters.entrySet()) {
            int key = entry.getKey();
            char value = entry.getValue();
            builderAnagramString.insert(key, value);
        }

        textFragments[i] = builderAnagramString.toString(); 
        stringBuilder.append(textFragments[i]); 

        if (i != (textFragments.length - 1)) {
            stringBuilder.append(" ");
        }
        mapNonLetters.clear();
    }
    return stringBuilder.toString();
}

此方法搜索用户文本的每个字母的所有非字母

/**
 * Method search symbols
 * @param arrayCharacters
 * @return HashMap with symbols found from elements of array
 */
public HashMap<Integer, Character> saerchNonLetters(char[] arrayCharacters) {

    HashMap<Integer, Character> mapFoundNonLetters = new HashMap<Integer, Character>();

        for (int j = 0; j < arrayCharacters.length; j++) {
            //Letters lay in scope 65-90 (A-Z) and 97-122 (a-z) therefore other value is non-letter
            if (arrayCharacters[j] < 65 || (arrayCharacters[j] > 90 && arrayCharacters[j] < 97) ||
                    arrayCharacters[j] > 122) {
                mapFoundNonLetters.put(j, arrayCharacters[j]);
            }
        }
        return mapFoundNonLetters;
    }
}

2 个答案:

答案 0 :(得分:0)

public class Anagram {
public static void main(String[] args) {
    String text = "!Hello123 ";
    char[] chars = text.toCharArray();

    int left = 0;
    int right = text.length() - 1;

    while (left < right) {
        boolean isLeftLetter = Character.isLetter(chars[left]);
        boolean isRightLetter = Character.isLetter(chars[right]);
        if (isLeftLetter && isRightLetter) {
            swap(chars, left, right);
            left++;
            right--;
        } else {
            if (!isLeftLetter) {
                left++;
            }

            if (!isRightLetter) {
                right--;
            }
        }
    }

    String anagram = new String(chars);
    System.out.println(anagram);
}

private static void swap(char[] chars, int index1, int index2) {
    char c = chars[index1];
    chars[index1] = chars[index2];
    chars[index2] = c;
}

}

答案 1 :(得分:0)

如果我理解正确并且您只需要1个字谜,这应该有效:

String originalString = "This is 1 sentence with 2 numbers!";
System.out.println("original: "+originalString);

// make a mask to keep track of where the non letters are
char[] mask = originalString.toCharArray();
for(int i=0; i<mask.length; i++)
  mask[i] = Character.isLetter(mask[i]) ? '.' : mask[i];
System.out.println("mask:     "+ new String(mask));

// remove non letters from the string
StringBuilder sb = new StringBuilder();
for(int i=0; i< originalString.length(); i++) {
  if(mask[i] == '.')
    sb.append(originalString.charAt(i));
}

// find an anagram
String lettersOnlyAnagram = sb.reverse().toString();

// reinsert the non letters at their place
int letterIndex = 0;
for(int i=0; i<mask.length; i++) {
  if(mask[i] == '.') {
    mask[i] = lettersOnlyAnagram.charAt(letterIndex);
    letterIndex++;
  }
}

String anagram = new String(mask);
System.out.println("anagram:  "+ anagram);

打印出来:

original: This is 1 sentence with 2 numbers!
mask:     .... .. 1 ........ .... 2 .......!
anagram:  sreb mu 1 nhtiwecn etne 2 ssisihT!