华为OD2023(A卷)基础题2【字符串重新排列】

题2.字符串重新排列

给定一个字符串s,s包括以空格分隔的若干个单词,请对s进行如下处理后输出:
1、单词内部调整:对每个单词字母重新按字典序排序
2、单词间顺序调整:
1)统计每个单词出现的次数,并按次数降序排列
2)次数相同,按单词长度升序排列
3)次数和单词长度均相同,按字典升序排列
请输出处理后的字符串,每个单词以一个空格分隔。输入描述:
一行字符串,每个字符取值范围:【a—zA—z0—9】以及空格,字符串长度范围:【1,1000】
例1:
输入 This is an apple
输出 an is This aelpp

主要考察算法和数据结构:字符串排序、对象的使用、数组的排序和遍历

以下是按步骤罗列的解题思路:

  1. 首先将输入的字符串按照空格分割成单词数组;
  2. 对每个单词进行内部调整,即重新按照字典序排序。可以使用现成的排序函数,也可以手写一段排序代码;
  3. 使用一个对象来统计每个单词出现的次数,并按要求进行排序。排序时,可以使用自定义比较函数来实现多级排序,需要注意考虑次数、长度和字典序的优先级关系。最后将排完序的单词拼接成字符串输出。

java实现如下:

import java.util.*;

public class Main {
      public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();

        // 将字符串按空格分割成单词
        String[] words = s.split(" ");

        // 对每个单词内部进行字典序排序
        for (int i = 0; i < words.length; i++) {
            char[] wordChars = words[i].toCharArray();
            Arrays.sort(wordChars);
            words[i] = new String(wordChars);
        }

        // 统计每个单词出现的次数
        Map<String, Integer> wordCountMap = new HashMap<>();
        for (String word : words) {
            wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
        }

        // 对单词排序,排序规则如题目所述
        Arrays.sort(words, (w1, w2) -> {
            int count1 = wordCountMap.get(w1);
            int count2 = wordCountMap.get(w2);
            if (count1 != count2) {
                return count2 - count1; // 次数相同,按次数降序排列
            } else if (w1.length() != w2.length()) {
                return w1.length() - w2.length(); // 次数相同,按单词长度升序排列
            } else {
                return w1.compareTo(w2); // 次数和单词长度均相同,按字典升序排列
            }
        });

        // 输出处理后的字符串
        for (int i = 0; i < words.length; i++) {
            if (i != 0) {
                System.out.print(" ");
            }
            System.out.print(words[i]);
        }
    }
}

C++实现如下:

#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>

using namespace std;

string wordSort(const string& word) {
    /**
     * 对每个单词的字母重新按字典序排序
     */
    string sorted_word = word;
    sort(sorted_word.begin(), sorted_word.end());
    return sorted_word;
}

string rearrangeString(const string& s) {
    /**
     * 对字符串s进行重新排列
     */
    // 将字符串s分割成单词列表
    vector<string> words;
    string word;
    for (char c : s) {
        if (c == ' ') {
            words.push_back(word);
            word = "";
        } else {
            word += c;
        }
    }
    if (!word.empty()) {
        words.push_back(word);
    }

    // 统计每个单词出现的次数
    unordered_map<string, int> word_count;
    for (const string& word : words) {
        word_count[word]++;
    }

    // 按照要求排序
    sort(words.begin(), words.end(), [&](const string& w1, const string& w2) {
        int count_compare = word_count[w2] - word_count[w1];
        if (count_compare != 0) {
            return count_compare > 0;
        }
        int length_compare = w1.length() - w2.length();
        if (length_compare != 0) {
            return length_compare < 0;
        }
        return wordSort(w1) < wordSort(w2);
    });

    // 返回结果
    string result = "";
    for (int i = 0; i < words.size(); i++) {
        result += words[i];
        if (i != words.size() - 1) {
            result += " ";
        }
    }
    return result;
}

int main() {
    string s;
    getline(cin, s);
    cout << rearrangeString(s) << endl;
    return 0;
}

python实现如下:

def word_sort(word):
    """
    对每个单词的字母重新按字典序排序
    """
    return ''.join(sorted(word))


def rearrange_string(s):
    """
    对字符串s进行重新排列
    """
    # 将字符串s分割成单词列表
    words = s.split(' ')

    # 统计每个单词出现的次数
    word_count = {}
    for word in words:
        if word not in word_count:
            word_count[word] = 1
        else:
            word_count[word] += 1

    # 按照要求排序
    sorted_words = sorted(word_count.keys(), key=lambda w: (-word_count[w], len(w), word_sort(w)))

    # 返回结果
    return ' '.join(sorted_words)

JavaScript

function wordSort(word) {
    /* 对每个单词的字在这里插入代码片*/
         const sortedWord = word.split('').sort().join('');
    return sortedWord;
}

function rearrangeString(s) {
    /**
     * 对字符串s进行重新排列
     */
    // 将字符串s分割成单词列表
    const words = s.trim().split(' ');

    // 统计每个单词出现的次数
    const wordCount = {};
    for (const word of words) {
        wordCount[word] = (wordCount[word] || 0) + 1;
    }

    // 按照要求排序
    words.sort((w1, w2) => {
        const countCompare = wordCount[w2] - wordCount[w1];
        if (countCompare !== 0) {
            return countCompare;
        }
        const lengthCompare = w1.length - w2.length;
        if (lengthCompare !== 0) {
            return lengthCompare;
        }
        return wordSort(w1).localeCompare(wordSort(w2));
    });

    // 返回结果
    return words.join(' ');
}

// 测试代码
const s = 'This is an apple';
console.log(rearrangeString(s)); // 输出:an is This aelpp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值