【问题标题】:Reversing characters in each word in a sentence - Stack Implementation反转句子中每个单词中的字符 - Thinbug
【发布时间】:2012-07-17 16:48:54
【问题描述】:

这段代码在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 ---> sihT si a ecnetnes

【问题讨论】:

  • 倒转句子中的单词和句子中的字符之间存在细微差别。您想归档两者中的哪一个?
  • 我想反转句子中每个单词中的字符,同时保持相同的单词顺序。你可以说这是作业——我只是在网上寻找问题,以提高我对堆栈和队列的理解。
  • 您是否尝试过检查sentence 的值是什么,和/或Scanner.next() 的文档说它会做什么?
  • next() 只得到一个字。你的双循环在第一轮之后没有做任何事情。
  • 如果是作业,就这样标记。

标签: java stack reverse


【解决方案1】:

根据对原始帖子的修改,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. 当输入字符串为空时,从堆栈中弹出每个字符并打印到屏幕上。

所以:

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

【讨论】:

  • 可能有两个循环,一个用于反转字符,然后一个用于反转单词。 OP希望句子的词序相同,每个词颠倒
  • @Jake223 -- OP 更改了他的帖子。原文表示一个完全颠倒的句子。我将编辑我的回复。
【解决方案2】:

我假设您希望您的代码做的是依次反转每个单词,而不是整个字符串。所以,给定输入 example sentence 你希望它输出 elpmaxe ecnetnes not ecnetnes elpmaxe

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

如果你想输入一个完整的句子,把System.in包裹起来如下:

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

并致电reader.readLine()

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    假设您已经在 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 已经指出了。 (就个人而言,除非速度是问题,否则我会使用 Scanner 而不是 BufferedReader,但这只是我的看法。)

    【讨论】:

      【解决方案4】:
      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;
      }
      

      }

      【讨论】:

      • 考虑在您的答案中添加描述
      • 不要只写代码,试着说出你的答案或解释它。
      【解决方案5】:

      公共类 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();   
      }
      

      }

      【讨论】:

        【解决方案6】:
        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

        【讨论】:

        • 您能否为您的答案添加更多解释?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 2021-04-28
        相关资源
        最近更新 更多