zoukankan      html  css  js  c++  java
  • 5413.重新排列句子中的单词

    image-20200517154537330

    提示

    • text 以大写字母开头,然后包含若干小写字母以及单词间的单个空格。
    • 1<=text.length<=10^5

    冒泡排序

    思路

    • 排序肯定能解决问题 当时用的是冒泡排序 O(n^2)
    /**
     * 1000ms
     */
    public String arrangeWords(String text) {
        String s1 = text.toLowerCase();
        String[] s = s1.split(" ");
        int len=s.length;
        for(int i=0;i<len-1;i++){
            for(int j=0;j<len-i-1;j++){
                if(s[j].length()>s[j+1].length()){
                    String tmp=s[j];
                    s[j]=s[j+1];
                    s[j+1]=tmp;
                }
            }
        }
        char[] cs=s[0].toCharArray();
        cs[0]-=32;
        String first=String.valueOf(cs);
        String ans=first;
        for(int i=1;i<len;i++){
            ans+=" "+s[i];
        }
        return ans;
    }
    

    根据长度建立字符串长度数组

    参考 清风:根据长度建立字符串长度数组

    • 根据字符串分割将对应长度的字符串 放入声明对应下标的数组字符串中,然后遍历。(很妙!)

    代码

    /*
     * 时间复杂度 O(n)
     * 60ms
     */
    public String arrangeWords(String text) {
             
           String[] strs = new String[(int)Math.pow(10, 5) + 1];
            String[] inputStrs = text.split(" ");
    
            int count = 1;
            for (String str : inputStrs) {
                //下标即为单词的长度
                int index = str.length();
                //如果是首位单词
                if (count == 1) {
                    strs[index] = str.toLowerCase();
                }else {//(同样的长度下)在已有的基础上 继续添加单词
                    /*
                    if (strs[index] == null) {
                        strs[index] =  str;
    
                    } else {
                        strs[index] = strs[index] + " "+ str;
                    }*/
                    strs[index] = (strs[index] == null ? str : (strs[index] + " " + str));
                }
                count++;
            }
    		
         	//拼接
            StringBuilder builder = new StringBuilder();
            for (String res : strs) {
                if (res == null || res.equals("")) continue;
                builder.append(" " + res);
            }
         	//首单词的首字母大写
            String firstChar =  builder.toString().trim().charAt(0)+"";
            String leftStr = builder.toString().trim().substring(1);
            return firstChar.toUpperCase()+leftStr;
        }
    }
    
  • 相关阅读:
    SD卡测试
    测试人员可能会遇到的问题
    HDU 1024 Max Sum Plus Plus
    HDU 1176 免费馅饼
    HDU 1257 最少拦截系统
    HDU 1087 Super Jumping! Jumping! Jumping!
    poj 1328 Radar Installation
    poj 1753 Flip Game
    HDU 1003 Max Sum
    HDU 5592 ZYB's Premutation(BestCoder Round #65 C)
  • 原文地址:https://www.cnblogs.com/yh-simon/p/12905676.html
Copyright © 2011-2022 走看看