颠倒句子中每个单词的字符而不反转单词顺序

时间:2016-01-15 18:15:27

标签: java arrays loops stack

我有这个代码应该做标题所说的,反转字符的顺序而不改变单词的顺序:

package stackTests;

import java.util.Scanner;
import java.util.Stack;


public class StackTest
{
  Stack<Character> stack;

  public StackTest()
  {
    stack = new Stack<Character>();
  }

  public String reverseString(String str)
  {
    int start = 0;
    int start2 = 0;
    int size;
    char space = ' ';
    char[] cArr;
    Scanner scan = new Scanner(str);
    cArr = str.toCharArray();
    for (; start < cArr.length; start++)
    {
      if(cArr[start] == space || start == cArr.length - 1)
      {
        for (; start2 < stack.size(); start++)
        {
          System.out.print(stack.pop());
        }
      }
      else
      {
        stack.push(cArr[start]);
      }
      start2 = 0;
    }
    return str;
  }
}

如果我输入一个像“Hello”这样的单词,它会正常工作 - 它会输出“olleH” - 但是一旦它变得比一个单词更复杂,它就会开始输出一些奇怪的东西。“你好我的名字是“输出”奥勒姆“。我是Stack的新手,这是我第一次使用它们。我不确定是否存在逻辑错误或Stack的使用不当。

3 个答案:

答案 0 :(得分:3)

如果你必须使用堆栈,我会遵循这样的算法:

String myString = "Hello World";
Stack<Character> stack = new Stack<Character>();
StringBuilder sb = new StringBuilder();
String[] splitString = myString.split(" ");

//Iterate through each word in the string
for(String s : splitString){

    //Push each character of the word into LIFO stack
    for(char c : s.toCharArray()){
        stack.push(c);
    }

    //Build new string with reverse ordered characters
    while(!stack.isEmpty()){
        sb.append(stack.pop());
    }

    //Append a space as long as it's not the last word of the original string
    if(!s.equals(splitString[splitString.length - 1]))
        sb.append(" ");
}

//Print the new string
System.out.println(sb.toString());

我不确定效率对您有何影响,但此算法可以在线性时间内工作,其中n是字符串中的字符数。

答案 1 :(得分:3)

你没有输出原始空格,这就是你看到奇怪结果的原因

这里是固定版本:

public static void reverseString(final String str) {
    final Stack<Character> stack = new Stack<>();
    for (int i = 0; i < str.length(); i++) {
        final char c = str.charAt(i);
        if (c == ' ') {
            while (!stack.isEmpty())
                System.out.print(stack.pop());
            System.out.print(' ');
        } else
            stack.push(c);
    }
    while (!stack.isEmpty())
        System.out.print(stack.pop());
}

没有堆叠的另一个版本,具有就地替换:

public static void reverseString(final String str) {
    final char[] chars = str.toCharArray();
    int start = 0;
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] == ' ') {
            reverse(chars, start, i - 1);
            start = i + 1;
        }
    }
    reverse(chars, start, chars.length - 1);
    System.out.println(new String(chars));
}

private static void reverse(final char[] chars, int s, int e) {
    while (s < e) {
        final char t = chars[s];
        chars[s] = chars[e];
        chars[e] = t;
        s++;
        e--;
    }
}

答案 2 :(得分:0)

以下是如何在不使用任何额外空间(不使用堆栈)的情况下就地执行此操作:

public class ReverseWordsInplace {

    public static void main(String[] args) {
        reverseWords(new StringBuilder("This is a test"));
    }

    public static void reverseWords(StringBuilder s) {
        StringBuilder str = new StringBuilder(s);
        int startWordIndex = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ' ' || str.length() - 1 == i) {
                int x = 0;
                int endWordIndex = str.charAt(i) == ' ' ? i - 1 : i;
                while (endWordIndex - x > startWordIndex + x) {
                    char c1 = str.charAt(startWordIndex + x);
                    char c2 = str.charAt(endWordIndex - x);
                    str.setCharAt(startWordIndex + x, c2);
                    str.setCharAt(endWordIndex - x, c1);
                    x++;
                }
                startWordIndex = i + 1;
            }
        }
        System.out.println(str);
    }
}

输出:

  

sihT si a tset