简体   繁体   English

如何反转字符串中的每个字符?

[英]How do i reverse each character in a string?

class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }


    }
    return build.toString();
}
}

I am having trouble understanding why this doesn't work. 我无法理解为什么这不起作用。 I went through the entire code a couple of times but there seems to be an issue. 我经历了几次整个代码,但似乎有一个问题。

Input : "Let's take LeetCode contest" my answer: " s'teL ekat s'teL edoCteeL ekat s'teL " correct answer: "s'teL ekat edoCteeL tsetnoc" whats going on? 输入: "Let's take LeetCode contest"我的答案: " s'teL ekat s'teL edoCteeL ekat s'teL "正确答案: "s'teL ekat edoCteeL tsetnoc"最新情况如何?

There are several problems: 有几个问题:

  • You set current to the current position, and then iterate down to 0 append characters. 您将current位置设置为当前位置,然后向下迭代到0追加字符。 Instead of going down to 0, you iterate until the beginning of the last word. 而不是下降到0,你迭代直到最后一个单词的开头。 Alternative, iterate until the previous ' ' character. 替代方案,迭代直到前一个' '字符。

  • You only append something after seeing a ' ' character. 你只看到一个' '字符后附加一些东西。 What will happen at the end of the sentences? 在句子结尾会发生什么? As i goes over the letters in the last word, there will be no more ' ' characters, and so the last word will never get appended. i查看最后一个单词中的字母时,将不再有' '字符,因此最后一个单词永远不会被附加。 To handle this case, you would need to add some logic after the for-loop to check if there is an unwritten word, and append it reversed. 要处理这种情况,您需要在for循环之后添加一些逻辑来检查是否存在未写入的单词,并将其反转。

A simpler approach is to take advantage of the StringBuilder 's ability to insert characters at some position. 一种更简单的方法是利用StringBuilder在某个位置插入字符的能力。 You could track the beginning position of the current word, and as you iterate over the characters, insert if it's not ' ' , or else append a ' ' and reset the insertion position. 您可以跟踪当前单词的开始位置,并在迭代字符时插入,如果它不是' ' ,或者附加' '并重置插入位置。

StringBuilder build = new StringBuilder();
int current = 0;
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c == ' ') {
        build.append(' ');
        current = i + 1;
    } else {
        build.insert(current, c);
    }
}
return build.toString();

Use a StringBuilder to reverse each word in your String : 使用StringBuilder来反转String中的每个单词:

 String input = "Let's take LeetCode contest";

    String[] split = input.split(" +");
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < split.length; i++) {

        output.append(new StringBuilder(split[i]).reverse());
        if(i<input.length()-1)
        output.append(" ");
    }

    System.out.println(output);

First, you skip over index 0. Put these lines at the end of your method to avoid this: 首先,跳过索引0.将这些行放在方法的末尾以避免这种情况:

count++; 
current = count;

You might need a variable to track where the current word began. 您可能需要一个变量来跟踪当前单词的开始位置。 For example, declare one along with count and current like this: 例如,像count和current一样声明一个:

int wordStart = 0;

Then, when you finish processing a word, set wordStart to point to the first character of the next word. 然后,当您处理完一个单词后,将wordStart设置为指向下一个单词的第一个字符。 I would put that after the while loop, here: 我会把它放在while循环之后,这里:

build.append(s.charAt(i));
wordStart = count + 1;

You will also need to change this: while(current > 0){ to this: while(current >= wordStart) 你还需要改变这个: while(current > 0){ to this: while(current >= wordStart)

Also: you don't need count. 另外:你不需要数数。 The variable i is the exact same thing. 变量i完全相同。

You can use stream-api for your goal: 您可以使用stream-api来实现目标:

Stream.of(str.split(" "))
            .map(s -> new StringBuilder(s).reverse().toString())
            .reduce((s1, s2) -> s1 + " " + s2)
            .orElse(null);

This is the easy way: 这是简单的方法:

return Arrays.stream(s.split(" " ))
        .map(StringBuilder::new)
        .map(StringBuilder::reverse)
        .map(StringBuilder::toString)
        .collect(Collectors.joining(" "));

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

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