zoukankan      html  css  js  c++  java
  • 一个句子,找出最字符最少的关键词

     1     //一个句子,找出最字符最少的关键词,eg practice makes perfect
     2     
     3     public static void main(String[] args) {
     4         int minLen=0;
     5         String str=null;
     6         String sentence="practice makes perfect";
     7         String[] strings=sentence.split(" ");
     8         /*for(int i=0;i<strings.length;++i){
     9             System.out.println(strings[i]);
    10         }*/
    11         minLen=strings[0].length();
    12         str=strings[0];
    13         for(int i=1;i<strings.length;++i){
    14             if(strings[i].length()<minLen){
    15                 minLen=strings[i].length();
    16                 str=strings[i];
    17             }
    18         }
    19         System.out.println("The min keyword is "+str+"
    it's length is "+str.length());
    20     }
    21 
    22 }
    运行结果
    The min keyword is makes
    it's length is 5

    注,如果空格个数多于一个,eg. practice     makes perfect

    运行结果:

    The min keyword is
    it's length is 0

    把第7行改为

    String[] strings=sentence.split("\s{1,}");
    或者
    String[] strings=sentence.split("\s+");
    就可以了,参考 http://maoa.cn/?post=406


    hashmap:
     1     public static void main(String[] args) {
     2         String sentence="practice  makes perfect";
     3         String[] strings=sentence.split("\s+");
     4         HashMap<Integer,String> map = new HashMap<Integer,String>();
     5         for(int i=0;i<strings.length;++i){
     6             map.put(strings[i].length(), strings[i]);
     7         }
     8         Iterator<Entry<Integer,String>> iter=map.entrySet().iterator();
     9         Entry<Integer,String> entry=iter.next();
    10         int minLen=entry.getKey();
    11         String str=entry.getValue();
    12         while(iter.hasNext()){
    13             entry=iter.next();
    14             if(entry.getKey()<minLen){
    15                 minLen=entry.getKey();
    16                 str=entry.getValue();
    17             }
    18         }
    19         System.out.println("The min keyword is "+str+"
    it's length is "+str.length());
    20     }
    
    
    


  • 相关阅读:
    Gym-101128D:Dice Cup
    C++内联汇编,输出人物名字
    钩子
    列表控件ListBox关联的MFC中的类:CListBox
    高级列表控件ListCtrl关联的MFC中的类:CListCtrl
    菜单复选及窗口置顶
    MFC学习之EDIT控件初始化
    dbgprint_Mine 调试输出
    64位内联汇编
    win7下提权代码
  • 原文地址:https://www.cnblogs.com/crane-practice/p/3669714.html
Copyright © 2011-2022 走看看