扫描并抓取特定令牌

时间:2015-10-18 20:38:53

标签: java algorithm palindrome

我在几天内测试的时候遇到了麻烦。

全部使用堆栈和队列

Sample.txt : My mom and dad both think I will do good at my gig tomorrow.

我有一个附加文件的GUI,并为Palindromes解析文件。我想举个例子,

我可以找到mom作为回文,并且由于mom.length()是==到3,我会从mom抓取第三个令牌,在这种情况下会是both。我能够正确地抓住所有这些回文,只是不知道我将如何遍历我尚未“阅读”的标记?

我的方法是,

public void fileDecode() throws FileNotFoundException
    {


            while(scanInput.hasNext())
            {
                int counter = 0;
                int nextPalindrome = 0;
                String token = scanInput.next();
                Stack<Character> stk = new Stack<Character>();
                Queue<Character> que = new LinkedList<Character>();
                for (int i = 0; i < token.length(); ++i)
                {
                    stk.push(token.charAt(i));
                    que.add(token.charAt(i));

                }
                for (int j = 0; j < token.length(); ++j)
                {
                        char tempStk = stk.pop();
                        char tempQue = que.remove();

                        if (tempStk == tempQue)
                        {
                            counter++;
                        }
                }

                if (counter == token.length())
                {
                   //build.append(token + " ");  #if i want to see the palindromes
                    nextPalindrome = token.length(); //the length/distance of the token desired
                } 

            }  
        }
    }

2 个答案:

答案 0 :(得分:0)

实现相同功能的简单解决方案

public class Test {

    public static void main(String[] args) throws Exception
    {

         Scanner sc = new Scanner(System.in);
         while ( sc.hasNext()){
             String str = sc.nextLine();
             String words[] = str.split(" ");
             for ( int i=0; i < words.length; i++){
                 String reverseWord = new StringBuffer(words[i]).reverse().toString();
                 System.out.println("word:reverseWord:Palindrome:"+words[i]+":"+reverseWord+":"+words[i].equals(reverseWord));
             }
         }

  }

}

修改

1)读取行并分成单词数组

2)对于每个单词,使用StringBuffer()和reverse()方法并获取反向字符串

3)比较两个字符串是否相等。如果相等,那就是回文。

答案 1 :(得分:0)

  

我不知道如何遍历我尚未“阅读”的令牌?

您阅读并跳过它们。只需使用一个通常为0的局部变量,但是一旦找到回文,就可以将其设置为回文长度。然后在检查逻辑之前检查此变量并继续循环,如果它大于0。

// Idea: there are 3 cases:
// 1. tokensToSkip is 0: process as normal (check for palindromeness)
// 2. tokensToSkip is 1: decrement it to 0, but process as normal
// 3. tokensToSkip is 2, 3, 4...: decrement it and skip (continue the while)
// Note that tokensToSkip will never be negative.

// Will skip tokensToSkip - 1 tokens
int tokensToSkip = 0;
while(scanInput.hasNext()) {
    String token = scanInput.next();
    // instead of the next two lines we could just have:
    //     if (--tokensToSkip > 0) continue;
    // only once, notice the -- operator in front.
    //
    // This would almost always work, but if tokensToSkip = Integer.MIN_VALUE
    // decrementing it will cause negative overflow and thus tokensToSkip will
    // become Integer.MAX_VALUE! To prevent this we have a check.
    if (tokensToSkip > 0) tokensToSkip--;

    // here tokensToSkip is already decremented, so this check is different
    // from the one above. For example is tokensToSkip == 1 before the line
    // above, now it is tokensToSkip == 0 and this second check fails.
    if (tokensToSkip > 0) continue;
    if (isPalindrome(token)) {
        tokensToSkip = token.length();
    }
    // ... other stuff ...
}

顺便说一句,实现isPalindrome()的更有效方法是:

static boolean isPalindrome(String s) {
    for (int i = 0; i < s.length() / 2; i++) {
        if (s.charAt(i) != s.charAt(s.length() - i - 1)) {
            return false;
        }
    }
    return true;
}