2013-10-11 45 views
0

所以我的計劃是關於語言L = {'w$w' : w是一個字符超過$, w' = reverse(w)}堆棧處理語言recognizng字符串,java程序

所以其他可能的空字符串時,像HOD $ DOH被送到isINlanguage函數的參數中,應該返回true,但我的程序只是停止和掛起犯規了放東西

import java.util.Stack; 


public class Stacks 
{ 


public static void main(String[] args){ 
boolean eval = isInLanguage("sod$dos"); 

System.out.println(eval); 


} 




static // astack.createStack(); 
    boolean isInLanguage(String aString){ 
    Stack<Character> aStack = new Stack<>(); 


    int i = 0; 
    char ch = aString.charAt(i); 
    while (ch != '$') { 
     aStack.push(ch); 
     i++; 
    } 
    //Skip the $ 
    ++i; 

    // match the reverse of w 
    boolean inLanguage = true; // assume string is in language 
    while (inLanguage && i < aString.length()) { 
     char stackTop; 
     ch = aString.charAt(i);; 
     try { 
      stackTop = (char) aStack.pop(); 
      if (stackTop == ch) { 
       i++; 
      } else { 
       // top of stack is not ch(Charecter do not match) 
       inLanguage = false; // reject string 

      } 
     } catch (StackException e) { 
      // aStack.poo() failed, astack is empty (first, half of Stirng 
      // is short than second half) 

      inLanguage = false; 
     } 
    } 

    if (inLanguage && aStack.isEmpty()) { 
     return true; 
    } 
    else{ 
     return false; 

    } 
} 
} 
+0

這種轉換不是必需的:stackTop =(char)aStack.pop(); – TEK

+0

不投,我得到了螺紋 「異常‘主要’java.lang.Error的:未解決的問題,編譯: \t類型不匹配:不能從對象轉換爲char \t在Stacks.isInLanguage(Stacks.java:33) \t at Stacks.main(Stacks.java:6)' – ClearMist

回答

2

你是不是重置chwhile循環到下一個字符:

while (ch != '$') { 
    aStack.push(ch); 
    i++; 
    ch = aString.charAt(i); // Add this 
} 

此外,在try塊內,轉換不是必需的。分配:

stackTop = (char) aStack.pop(); 

...是更好的寫法如下:

stackTop = aStack.pop(); 

順便說一句,你真的複雜化你的任務,通過使用boolean變量,try-catch塊。不要讓stack.pop()發生任何異常。相反,只有在堆棧不空時才彈出一個元素。此外,只要您發現字符串不匹配所需的語言,就可以直接返回,因此不需要布爾變量。

我會修改你的方法:

static boolean isInLanguage(String aString){ 
    Stack<Character> aStack = new Stack<>(); 

    int i = 0; 
    char ch; 

    // This is simplified way to write your first while loop 
    // Read a character, move the index further, and test, all in single statement 
    while ((ch = aString.charAt(i++)) != '$') { 
     aStack.push(ch); 
    } 

    // Iterate till the stack is not empty 
    while (!aStack.isEmpty()) { 
     // Get next character in string, and pop an element from stack 
     // If they are not equal, return false 
     if (aString.charAt(i++) != aStack.pop()) { 
      return false; 
     } 
    } 

    // If we reach here, means stack is empty. Test if the index `i` has reached end of the string. 
    // If it reached the end of the string, return true, else return false (because there are still some characters to be processed). 
    return i == aString.length(); 
} 

aString.charAt(i++)將在指數i獲得字符,然後遞增i

+0

哇謝謝rohit,簡單的解決方案+1! – ClearMist

+0

@ClearMist查看真正簡化的代碼來完成任務。不需要額外的布爾變量就可以簡單得多,並且字符串長度檢查真的是冗餘的。 –

+0

@ClearMist您可以將答案標記爲已接受。 –