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

这段代码在main函数中:

 Scanner input = new Scanner(System.in); System.out.println("Type a sentence"); String sentence = input.next(); Stack stk = new Stack(); 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

根据对原始post的修改,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(); 

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

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

如果要输入整个句子,请按如下方式包装System.in

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

并调用reader.readLine()

希望这可以帮助。

假设你已经输入了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 == ',') {等等。)

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

 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; } 

}

公共课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 charStack = new Stack(); 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(); } 

}

 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传递