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     }
    
    
    


  • 相关阅读:
    归类常用控件GroupBox、TabControl、Expander
    ScrollViewer控件
    捕获鼠标位置
    5、标记拓展
    如何实现文件增量同步——算法
    常用的 Nand Flash 指令如下:
    Consistent Hashing算法
    循环冗余检验 (CRC) 算法原理
    yaffs2根文件系统的构建过程
    linux内存管理之uboot第一步
  • 原文地址:https://www.cnblogs.com/crane-practice/p/3669714.html
Copyright © 2011-2022 走看看