简体   繁体   English

使用链表或数组来反转Java中的字符串?

[英]Use linked list or array to reverse a string in Java?

I believe that we can use a for loop to reverse a string in Java. 我相信我们可以使用for循环来反转Java中的字符串。 Just like below: 就像下面这样:

String[] name = new String[10];

for(int i = name.length; i >0; i--){

    System.out.print(name[i-1]);

}

But another implementation is using LinkedList. 但是另一种实现方式是使用LinkedList。 So my understanding is to use LinkedList when the client is not sure how long the string array might increase dynamically. 因此,我的理解是在客户端不确定字符串数组可能会动态增加多长时间时使用LinkedList。 Is that correct? 那是对的吗?

A linked list of characters can be used to do this. 可以使用链接的字符列表来执行此操作。

In this instance, think of an array list as an array with unlimited length. 在这种情况下,将数组列表视为长度不受限制的数组。 For this, instead of adding values to the END of the array, we will add them to the BEGINNING of the linked list 为此,我们不是将值添加到数组的END,而是将它们添加到链接列表的BEGINNING

LinkedList<Character> linkedList = new LinkedList<Character>();
String str = "Hello World";

for (int i = 0; i < str.length(); i++) {
    linkedList.addFirst(str.charAt(i));
}

//whenever it is time to print the value....
for (char c : linkedList) {
    //Print it out, one character at a time
    System.out.print(c);
}

Whenever you have to add more characters to it, just use linkedList.addFirst() to append it to the beginning. 每当您需要向其添加更多字符时,只需使用linkedList.addFirst()将其追加到开头即可。

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

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