zoukankan      html  css  js  c++  java
  • 1451. Rearrange Words in a Sentence

    Given a sentence text (A sentence is a string of space-separated words) in the following format:

    • First letter is in upper case.
    • Each word in text are separated by a single space.

    Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

    Return the new text following the format shown above.

    Example 1:

    Input: text = "Leetcode is cool"
    Output: "Is cool leetcode"
    Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
    Output is ordered by length and the new first word starts with capital letter.
    

    Example 2:

    Input: text = "Keep calm and code on"
    Output: "On and keep calm code"
    Explanation: Output is ordered as follows:
    "On" 2 letters.
    "and" 3 letters.
    "keep" 4 letters in case of tie order by position in original text.
    "calm" 4 letters.
    "code" 4 letters.
    

    Example 3:

    Input: text = "To be or not to be"
    Output: "To be or to be not"
    

    Constraints:

    • text begins with a capital letter and then contains lowercase letters and single space between words.
    • 1 <= text.length <= 10^5
    class Solution {
        public String arrangeWords(String text) {
            String[] st = text.split(" ");
            st[0] = (char) (text.charAt(0) + 32) + st[0].substring(1);
            StringBuilder sb = new StringBuilder();
            Map<Integer, List<String>> map = new HashMap();
            for(String s: st){
                int l = s.length();
                if(map.get(l) == null){
                    map.put(l, new ArrayList());
                }
                map.get(l).add(s);
            }
            List<Integer> list = new ArrayList(map.keySet());
            Collections.sort(list);
            for(int i = 0; i < list.size(); i++){
                List<String> t = map.get(list.get(i));
                int tt = t.size();
                for(int j = 0; j < tt; j++) sb.append(t.get(j)).append(" ");
            }
            String res = sb.toString().trim();
            res = (char) (res.charAt(0) - 32) + res.substring(1);
            return res;
        }
    }

    先全部变成小写然后split,再把string按长度添加到map里面,然后按个添加string和空格,最后把首字母大写

  • 相关阅读:
    什么是Portal!
    Maven 让事情变得简单
    HTTP协议详解
    函数实现不放在头文件的原因,及何时可以放头文件的情况
    Linux中的内存管理(四)Heap
    寿星万年历Lua实现
    TCP epoll触发后只accept一次带来的问题
    生产者消费者问题
    Windows SDK 实现不规则窗口
    论迭代式的产品开发方法
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12908318.html
Copyright © 2011-2022 走看看