给定一个字符串s
,s
包括以空格分隔的若干个单词,请对s
进行如下处理后输出:
请输出处理后的字符串,每个单词以一个空格分隔。
一行字符串,每个字符取值范围:[a-zA-z0-9]
以及空格,字符串长度范围:[1,1000]
输出处理后的字符串,每个单词以一个空格分隔。
This is an apple
an is This aelpp
My sister is in the house not in the yard
in in eht eht My is not adry ehosu eirsst
本题要求对一个给定的字符串进行两个方面的处理:单词内部字母顺序调整和单词间顺序调整。以下分别解释各语言实现的思路和复杂度分析。
首先,对于输入的字符串,我们需要将其拆分成单词。大多数语言都有内置的字符串分割方法,如Python的split()
、Java的split()
、JavaScript的split()
、C++的istringstream
和Go的strings.Split()
。
接下来,我们需要统计每个单词的出现次数。这可以使用哈希表(例如Python的字典,Java的HashMap,JavaScript的Map,C++的unordered_map,Go的map)实现。同时,我们使用一个数组或列表来存储每个独特单词的信息,如排序后的单词、出现次数和单词长度。
在统计单词信息的过程中,我们可以根据需求对单词内部的字母进行排序。大多数语言都有内置的排序方法,如Python的sorted()
、Java的Arrays.sort()
、JavaScript的Array.prototype.sort()
、C++的std::sort()
和Go的sort.Slice()
。
单词统计完成后,我们需要根据题目要求对单词数组进行排序。这里我们可以使用语言提供的排序方法,如Python的sort()
、Java的Collections.sort()
、JavaScript的Array.prototype.sort()
、C++的std::sort()
和Go的sort.Sort()
。我们需要自定义一个比较函数来实现题目要求的排序规则。
最后,我们遍历已排序的单词数组,并根据每个单词的出现次数构建一个新的单词数组。最后将新的单词数组连接为一个字符串输出。
时间复杂度:
空间复杂度:
在本题中,我们使用了哈希表来统计单词的出现次数,这使得算法具有较高的时空效率。对于大多数实际应用场景,这种实现能够在可接受的时间范围内给出正确的结果。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct {
char *word;
int count;
int length;
} Word;
int compare_word(const void *a, const void *b) {
const Word *word_a = (const Word *)a;
const Word *word_b = (const Word *)b;
if (word_a->count != word_b->count) {
return word_b->count - word_a->count;
}
if (word_a->length != word_b->length) {
return word_a->length - word_b->length;
}
return strcmp(word_a->word, word_b->word);
}
int compare_char(const void *a, const void *b) {
return (*(char *)a) - (*(char *)b);
}
int main() {
char s[1001];
fgets(s, 1001, stdin);
s[strcspn(s, "\n")] = 0;
Word words[1001];
int word_count = 0;
char *token = strtok(s, " ");
while (token != NULL) {
int found = 0;
for (int i = 0; i < word_count; i++) {
if (strcmp(words[i].word, token) == 0) {
words[i].count++;
found = 1;
break;
}
}
if (!found) {
words[word_count].word = token;
words[word_count].count = 1;
words[word_count].length = strlen(token);
word_count++;
}
token = strtok(NULL, " ");
}
qsort(words, word_count, sizeof(Word), compare_word);
for (int i = 0; i < word_count; i++) {
qsort(words[i].word, words[i].length, sizeof(char), compare_char);
for (int j = 0; j < words[i].count; j++) {
printf("%s", words[i].word);
if (i < word_count - 1 || j < words[i].count - 1) {
printf(" ");
}
}
}
printf("\n");
return 0;
}
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <sstream>
struct Word {
std::string word;
int count;
int length;
};
bool compare_word(const Word &a, const Word &b) {
if (a.count != b.count) {
return a.count > b.count;
}
if (a.length != b.length) {
return a.length < b.length;
}
return a.word < b.word;
}
int main() {
std::string s;
std::getline(std::cin, s);
std::unordered_map<std::string, int> word_map;
std::vector<Word> words;
std::istringstream iss(s);
std::string token;
while (iss >> token) {
std::string sorted_token = token;
std::sort(sorted_token.begin(), sorted_token.end());
if (word_map.count(sorted_token) == 0) {
word_map[sorted_token] = words.size();
words.push_back({sorted_token, 1, static_cast<int>(token.length())});
} else {
words[word_map[sorted_token]].count++;
}
}
std::sort(words.begin(), words.end(), compare_word);
for (size_t i = 0; i < words.size(); ++i) {
for (int j = 0; j < words[i].count; ++j) {
std::cout << words[i].word;
if (i < words.size() - 1 || j < words[i].count - 1) {
std::cout << ' ';
}
}
}
std::cout << std::endl;
return 0;
}
import java.util.*;
class Word {
String word;
int count;
int length;
public Word(String word, int count, int length) {
this.word = word;
this.count = count;
this.length = length;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
scanner.close();
String[] tokens = s.split(" ");
HashMap<String, Word> wordMap = new HashMap<>();
ArrayList<Word> words = new ArrayList<>();
for (String token : tokens) {
char[] tokenChars = token.toCharArray();
Arrays.sort(tokenChars);
String sortedToken = new String(tokenChars);
if (!wordMap.containsKey(sortedToken)) {
Word newWord = new Word(sortedToken, 1, token.length());
wordMap.put(sortedToken, newWord);
words.add(newWord);
} else {
wordMap.get(sortedToken).count++;
}
}
words.sort((a, b) -> {
if (a.count != b.count) {
return b.count - a.count;
}
if (a.length != b.length) {
return a.length - b.length;
}
return a.word.compareTo(b.word);
});
StringBuilder result = new StringBuilder();
for (Word word : words) {
for (int j = 0; j < word.count; j++) {
result.append(word.word);
if (words.indexOf(word) < words.size() - 1 || j < word.count - 1) {
result.append(" ");
}
}
}
System.out.println(result.toString());
}
}
from collections import defaultdict
class Word:
def __init__(self, word, count, length):
self.word = word
self.count = count
self.length = length
def compare_word(a, b):
if a.count != b.count:
return b.count - a.count
if a.length != b.length:
return a.length - b.length
return (a.word > b.word) - (a.word < b.word)
s = input().strip()
tokens = s.split()
word_map = {}
words = []
for token in tokens:
sorted_token = ''.join(sorted(token))
if sorted_token not in word_map:
new_word = Word(sorted_token, 1, len(token))
word_map[sorted_token] = new_word
words.append(new_word)
else:
word_map[sorted_token].count += 1
words.sort(key=lambda w: (-w.count, w.length, w.word))
result = []
for word in words:
result.extend([word.word] * word.count)
print(' '.join(result))
const readline = require('readline');
class Word {
constructor(word, count, length) {
this.word = word;
this.count = count;
this.length = length;
}
}
function compareWord(a, b) {
if (a.count !== b.count) {
return b.count - a.count;
}
if (a.length !== b.length) {
return a.length - b.length;
}
return a.word.localeCompare(b.word);
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('', (input) => {
const tokens = input.trim().split(' ');
const wordMap = new Map();
const words = [];
for (const token of tokens) {
const sortedToken = token.split('').sort().join('');
if (!wordMap.has(sortedToken)) {
const newWord = new Word(sortedToken, 1, token.length);
wordMap.set(sortedToken, newWord);
words.push(newWord);
} else {
wordMap.get(sortedToken).count++;
}
}
words.sort(compareWord);
const result = [];
for (const word of words) {
for (let j = 0; j < word.count; j++) {
result.push(word.word);
}
}
console.log(result.join(' '));
rl.close();
});
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strings"
)
type Word struct {
word string
count int
length int
}
type Words []Word
func (w Words) Len() int {
return len(w)
}
func (w Words) Swap(i, j int) {
w[i], w[j] = w[j], w[i]
}
func (w Words) Less(i, j int) bool {
if w[i].count != w[j].count {
return w[i].count > w[j].count
}
if w[i].length != w[j].length {
return w[i].length < w[j].length
}
return w[i].word < w[j].word
}
func main() {
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
tokens := strings.Split(input, " ")
wordMap := make(map[string]*Word)
words := make(Words, 0)
for _, token := range tokens {
sortedToken := sortString(token)
if word, exists := wordMap[sortedToken]; !exists {
newWord := &Word{sortedToken, 1, len(token)}
wordMap[sortedToken] = newWord
words = append(words, *newWord)
} else {
word.count++
}
}
sort.Sort(words)
result := make([]string, 0)
for _, word := range words {
for j := 0; j < word.count; j++ {
result = append(result, word.word)
}
}
fmt.Println(strings.Join(result, " "))
}
func sortString(s string) string {
chars := []byte(s)
sort.Slice(chars, func(i, j int) bool {
return chars[i] < chars[j]
})
return string(chars)
}