翻译句子中每个单词中的字符 - 堆栈实现

时间:2012-07-18 15:31:55

标签: java stack reverse

此代码位于main函数内:

Scanner input = new Scanner(System.in);

System.out.println("Type a sentence");
String sentence = input.next();

Stack<Character> stk = new Stack<Character>();
int i = 0;

while (i < sentence.length())
{
    while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
    {
        stk.push(sentence.charAt(i));
        i++;
    }
    stk.empty();
    i++;
}

这是empty()函数:

public void empty()
{
    while (this.first != null)
        System.out.print(this.pop());
}

它无法正常工作,因为输入example sentence我会收到此输出:lpmaxe。第一个字母缺失,循环停止,而不是通过空格计算到句子的下一部分。

我正在努力实现这一目标:

This is a sentence ---&gt; sihT si a ecnetnes

6 个答案:

答案 0 :(得分:3)

对原始帖子的每次修改,其中OP现在表明他的目标是撤销句子中单词的字母顺序,但是将单词保留在其初始位置。

我认为,最简单的方法是使用String split函数,遍历单词,并反转它们的顺序。

String[] words = sentence.split(" "); // splits on the space between words

for (int i = 0; i < words.length; i++) {
    String word = words[i];
    System.out.print(reverseWord(word));

    if (i < words.length-1) {
        System.out.print(" "); // space after all words but the last
    }
}

方法reverseWord定义为:

public String reverseWord(String word) {
    for( int i = 0; i < word.length(); i++) {
        stk.push(word.charAt(i));
    }
    return stk.empty();
}

empty方法已改为:

public String empty() {
    String stackWord = "";
    while (this.first != null)
        stackWord += this.pop();
    return stackWord;
}

原始回复

最初的问题表明,OP希望完全颠倒这句话。

你有一个双循环结构,你根本不需要它。

考虑这个逻辑:

  1. 从输入字符串中读取每个字符并将该字符推送到堆栈
  2. 当输入字符串为空时,从堆栈中弹出每个字符并将其打印到屏幕。
  3. 所以:

    for( int i = 0; i < sentence.length(); i++) {
        stk.push(sentence.charAt(i));
    }
    stk.empty();
    

答案 1 :(得分:1)

我认为您希望代码执行的操作是依次反转每个单词,而不是整个字符串。因此,根据输入example sentence,您希望输出elpmaxe ecnetnes 而不是 ecnetnes elpmaxe

您看到lpmaxe而不是elpmaxe的原因是因为您的内部while - 循环不处理字符串的最后一个字符,因为您有i < sentence.length() - 1代替i < sentence.length()。您只看到一个单词的原因是因为您的sentence变量仅包含输入的第一个标记。这就是Scanner.next()方法的作用;它读取下一个(默认情况下)以空格分隔的标记。

如果您想输入整个句子,请按以下方式结束System.in

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

并致电reader.readLine()

希望这有帮助。

答案 2 :(得分:0)

假设您已经在sentence中获得了输入,并且Stack对象被称为stk,这里有一个想法:

char[] tokens = sentence.toCharArray();
for (char c : tokens) {
    if (c == ' ') {
        stk.empty();
        System.out.print(c);
    } else  {
        stk.add(c);
    }
}

因此,它将一次扫描一个字符。如果我们击中一个空格字符,我们假设我们已经击中一个单词的结尾,反过来吐出该单词,打印该空格字符,然后继续。否则,我们将字符添加到堆栈并继续构建当前单词。 (如果您还想允许使用句点,逗号等标点符号,请将if (c == ' ') {更改为if (c == ' ' || c == '.' || c == ',') {之类的内容,等等。)

至于为什么你只得到一个字,darrenp已经指出了。 (就个人而言,除非速度是一个问题,否则我会使用扫描仪而不是BufferedReader,但这只是我的观点。)

答案 3 :(得分:0)

import java.util.StringTokenizer;
public class stringWork {
public static void main(String[] args) {
    String s1 = "Hello World";
    s1 = reverseSentence(s1);
    System.out.println(s1);
    s1 = reverseWord(s1);
    System.out.println(s1);
}
private static String reverseSentence(String s1){
    String s2 = "";
    for(int i=s1.length()-1;i>=0;i--){
        s2 += s1.charAt(i);
    }
    return s2;
}
private static String reverseWord(String s1){
    String s2 = "";
    StringTokenizer st = new StringTokenizer(s1);
    while (st.hasMoreTokens()) {
        s2 += reverseSentence(st.nextToken());
        s2 += " ";
    }
    return s2;
}

}

答案 4 :(得分:0)

公共课ReverseofeachWordinaSentance {

/**
 * @param args
 */
public static void main(String[] args) {
    String source = "Welcome to the word reversing program";

    for (String str : source.split(" ")) {
        System.out.print(new StringBuilder(str).reverse().toString());
        System.out.print(" ");
    }
System.out.println("");

    System.out.println("------------------------------------ ");
    String original = "Welcome to the word reversing program";
    wordReverse(original);
    System.out.println("Orginal Sentence :::: "+original);
    System.out.println("Reverse Sentence :::: "+wordReverse(original));
}

public static String wordReverse(String original){

    StringTokenizer string = new StringTokenizer(original);

    Stack<Character> charStack = new Stack<Character>();

    while (string.hasMoreTokens()){

    String temp = string.nextToken();

    for (int i = 0; i < temp.length(); i ++){

    charStack.push(temp.charAt(i));
}
    charStack.push(' ');
}

    StringBuilder result = new StringBuilder();
    while(!charStack.empty()){
    result.append(charStack.pop());
}

    return result.toString();   
}

}

答案 5 :(得分:0)

public class reverseStr {
public static void main(String[] args) {
    String testsa[] = { "", " ", "       ", "a ", " a", " aa bd  cs " };
    for (String tests : testsa) {
        System.out.println(tests + "|" + reverseWords2(tests) + "|");
    }
}

public static String reverseWords2(String s) {
    String[] sa;
    String out = "";
    sa = s.split(" ");
    for (int i = 0; i < sa.length; i++) {
        String word = sa[sa.length - 1 - i];
        // exclude "" in splited array
        if (!word.equals("")) {
            //add space between two words
            out += word + " ";
        }
    }
    //exclude the last space and return when string is void
    int n = out.length();
    if (n > 0) {
        return out.substring(0, out.length() - 1);
    } else {
        return "";
    }
}

}

这可以传递leetcode