简体   繁体   中英

What's the fastest way to only rotate certain elements in an array?

I'm writing a form of word scrambler for strings which takes all letters except for the first and last, and rotates their positions. However, I am supposed to only look at the second to second last letters. How should I only scramble from the second last letter to the second last letter?

eg scramble "string" to "srintg"

I can call Collections.rotate() on an array of characters created by splitting the string, but that will scramble the entire word.

List<String> newWordList = Arrays.asList(word.split(" "));
Collections.rotate(newWordList, -1);
String newWord = String.join("", newWordList);

I want to get the output "srintg", but instead I will get "rintgs".

Provided that your word is long enough for it to be sensible (at least four letters), you can make the approach you present work by rotating a sublist of your list:

Collections.rotate(newWordList.subList(1, newWordList.size() - 1), -1);

List.subList() creates a view of a portion of a List list for the exact purpose of avoiding the need for overloading List methods with versions that operate on indexed sub-ranges of the elements. That's "fast" in the sense of fast to write, and it's fairly clear.

If you are looking for "fast" in a performance sense, however, then splitting and joining strings seems ill-advised. Fast est is probably not something we can offer, as performance needs to be tested, but if I were looking for best performance then I would test at least these general approaches:

  • Work with an array form of your word
    1. Use String.toCharArray() to obtain your word's letters in array form.
    2. Use an indexed for loop to rotate the characters in the array.
    3. Construct a new String from the modified array (using the appropriate constructor).
  • Use a StringBuilder to assemble the word
    1. Create a StringBuilder with initial capacity equal to the word length.
    2. Iterate over the word's letters using a CharacterIterator , appending them to the builder in the order required. This can be done in a single pass.
    3. Obtain the result string from the builder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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