hdoj1004遇到的问题总结及源代码

来源:互联网 发布:淘宝未按约定发布商品 编辑:程序博客网 时间:2024/05/22 10:46

今天在做hdoj的1004题时自己测试感觉答案是正确的,但是就是死活过不了,一直wronganswer,看了半天自己写的代码,一直觉得没问题,在洗澡的时候突然想起我每次测试都是直接拷贝的给的示例输入,我用Scanner读入字符串是用的nextLine();这个方法是读取一行,包括空格,TAB,知道遇到回车换行结束,就是因为这个,在拷贝的时候中间有空格没注意导致一直wrong answer。想了想应该用next()方法输入字符串,next()方法是回到下一个分隔符的完整字符串。

 

next()与nextLine()的api解释public String next()Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Specified by:next in interface Iterator<String>
Returns:the next token
Throws:NoSuchElementException - if no more tokens are availableIllegalStateException - if this scanner is closed
See Also:Iterator
public String nextLine()Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.Returns:the line that was skipped
Throws:NoSuchElementException - if no line was foundIllegalStateException - if this scanner is closed

//代码,大家可以参考参考

importjava.util.*; public classMain{             public static void main(String[] args)       {              Scanner s = newScanner(System.in);              ArrayList<String> al = newArrayList<String>();              while (s.hasNext())              {                     int t = s.nextInt();                     if (0 == t)                            break;                     HashMap<String,Integer> hm = new HashMap<String, Integer>();                     while (t > 0)                     {                            t--;                            String str =s.next();                            int times;                            if(hm.containsKey(str))                            {                                   times =hm.get(str).intValue()+1;                            }else                                   times=0;                            hm.put(str, times);                     }                     Set<String> keys =hm.keySet();                     String ans = "";                     int max = -1;                     for(String str:keys)                     {                            int temp =hm.get(str).intValue();                            if(temp>max)                            {                                   max=temp;                                   ans = str;                            }                     }                     al.add(ans);              }              for(String str:al)              {                     System.out.println(str);              }              s.close();       }      }


0 0
原创粉丝点击