2012-07-18 4 views
0
이 코드는 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 영업 이익은 이제 그의 목표는 단어의 문자 순서를 반대로하는 것을 나타내는되어 원래의 게시물을 수정 당

+3

문장의 단어와 문장의 문자를 뒤집는 것과는 약간의 차이가 있습니다. 둘 다 무엇을 성취하고 싶니? –

+0

나는 같은 단어 순서를 유지하면서 문장의 각 단어의 문자를 뒤집고 싶다. 그리고 숙제라고 말할 수 있습니다. 스택 및 대기열에 대한 이해를 높이기 위해 온라인에서 질문을하고 있습니다. – amiregelz

+1

'sentence'의 값이 무엇인지, 그리고/또는 ['Scanner.next()'의 문서를 확인해 보았습니까? (http://docs.oracle.com/javase/6/docs/api/java /util/Scanner.html#next())는 그렇게 할 것이라고 말했습니다. –

답변

3

문장 안에서, 그러나 그들의 초기 위치에 단어를 남기십시오.

가장 간단한 방법은 문자열 split 함수를 사용하여 단어를 반복하고 명령을 역으로 수행하는 것입니다.

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

원래 응답

원래 질문 : empty 방법이 변경되었습니다

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

그리고 : 방법 reverseWord과 같이 정의된다

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

표시 그 OP는 그 문장을 완전히 뒤집고 싶었다.

정말 필요하지 않은 곳에 이중 루핑 구조가 있습니다.

  1. 입력 문자열이 비어있는 경우, 스택에서 각 문자를 팝업 화면에 인쇄 입력 문자열에서 각 문자를 읽고 스택
  2. 에 해당 문자를 눌러 :

    는이 논리를 생각해 보자.

그래서 :

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

2 개의 루프, 하나는 역순으로, 하나는 역순으로 반복합니다. OP는 같은 단어 순서로 문장을 원합니다. 각 단어가 반대로 바뀝니다. –

+0

@ Jake223 - OP가 자신의 게시물을 변경했습니다. 원본은 완벽하게 뒤집힌 문장을 나타 냈습니다. 나는 나의 응답을 편집 할 것이다. –

1

나는 당신이 원하는 것을 할 수있는 코드가 차례로 각 단어가 아닌 전체 문자열을 반대하는 것으로 가정합니다. 따라서 입력이 example sentence 인 경우 elpmaxe ecnetnes이 아닌ecnetnes elpmaxe이 출력되기를 원합니다. 당신이 i < sentence.length() - 1 대신 i < sentence.length()이 있기 때문에 당신의 내면의 while -loop 문자열의 마지막 문자를 처리하지 않기 때문에 대신 elpmaxelpmaxe를 참조

이유입니다.sentence 변수가 입력의 첫 번째 토큰으로 만 구성되어 있기 때문에 한 단어 만 표시되는 이유가 있습니다. 이것은 방법 Scanner.next()가하는 것이다; 공백으로 구분 된 다음 토큰 (기본값)을 읽습니다.

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

reader.readLine() 전화 : 입력하려는 경우

전체 문장은 다음과 같이 System.in을 마무리.

희망이 도움이됩니다.

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

따라서, 한 번에 하나 개의 문자를 스캔합니다

0

이미 sentence에 입력있어 가정 및 스택 객체가 stk라고, 여기에 생각입니다. 우리가 공백 문자를 친다면, 우리는 단어의 끝에 도달했다고 가정하고 그 단어를 역으로 내뱉어 그 공백 문자를 인쇄 한 다음 계속합니다. 그렇지 않으면 스택에 문자를 추가하고 현재 단어를 계속 작성합니다. (마침표, 쉼표 등과 같이 구두점을 허용하려면 if (c == ' ' || c == '.' || c == ',') { 등으로 변경하십시오.)

한 단어 만 가져 오는 이유는 darrenp가 이미 지적한 바입니다. (개인적으로, 속도가 문제가되지 않는 한 내가 대신의 BufferedReader의 스캐너를 사용 싶지만, 그건 그냥 제 생각입니다.)

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

을}

+0

답변에 설명 추가를 고려하십시오. –

+0

코딩 만하지 말고 답안에 대해 설명하거나 설명하십시오. –

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

}

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로 전달할 수 있습니다.

+0

답변에 더 많은 설명을 추가 할 수 있습니까? – DeadChex