对于给定的一个包含连续字母、连续数字及空格的字符串(不会出现字母和数字连在一起出现),实现字母部分按出现顺序排列而数字按照从小到达顺序排在最后一个字母的后面。
数据范围: 字符串长度满足 
进阶:空间复杂度
, 时间复杂度 )
进阶:空间复杂度
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param text_source string字符串 原始输入
* @return string字符串
*/
public String char_and_num_return (String text_source) {
if("".equals(text_source)){
return "";
}
String[] words = text_source.split(" ");
PriorityQueue<String> pq = new PriorityQueue<>(new Comparator<String>(){
public int compare(String a, String b){
return (int)(Long.parseLong(a) - Long.parseLong(b));
}
});
StringBuilder sb = new StringBuilder();
for(String word: words){
if(word.charAt(0) > 57){ // 首字符的ascii码大于57一定是字母item
sb.append(word).append(" "); // 字母字符串直接加入stringbuilder
}else{
pq.offer(word); // 数字字符串加入小根堆
}
}
// 将数字字符串按升序出队
while(!pq.isEmpty()) {
sb.append(pq.poll()).append(" ");
}
return sb.toString().trim();
}
}
public String char_and_num_return (String text_source) {
// write code here
String[] str = text_source.split(" ");
List s1 = new ArrayList();
List s2 = new ArrayList();
for(int i = 0;i<str.length;i++){
if(isNumber(str[i])){
s1.add(new Long(str[i]));
}else{
s2.add(str[i]);
}
}
Collections.sort(s1);
s2.addAll(s1);
StringBuffer sb = new StringBuffer();
sb.append(s2.get(0));
StringBuffer sb1 = new StringBuffer();
for(int i = 1;i<s2.size();i++){
sb.append(" "+s2.get(i));
}
sb1.append(sb);
return sb1.toString();
}
private boolean isNumber(String s){
Pattern pattern =Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(s).matches();
} //*.调用 String.split 方法切分字符串
//1.是字符串,字符串拼接
//2.是数字,添加到List,进行排序(注意数字过长,使用Long类型)
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已指定,请勿修改,直接返回方法规定的值即可
*
*
* @param text_source string字符串 原始输入
* @return string字符串
*/
public static String char_and_num_return(String text_source) {
// write code here
if ("".equals(text_source)) {
return "";
}
String[] params = text_source.split(" ");
List<Long> list = new ArrayList<>();
// String[] params = StringUtils.split(text_source, " ");
// int[] nums = new int[params.length];
// int cnt = 0;
String res = "";
for (String param : params) {
if (Character.isDigit(param.charAt(0))) {
//使用Long类型,避免数字过长抛出异常
Long l = Long.parseLong(param);
// Integer i = Integer.parseInt(param);
// nums[cnt++] = i;
list.add(l);
} else {
res += param + " ";
}
}
list.sort(new Comparator<Long>() {
@Override
public int compare(Long o1, Long o2) {
return o1.compareTo(o2);
}
});
for (Long l : list) {
res += l + " ";
}
// Arrays.sort(nums);
// for (int num : nums) {
// res += num + " ";
// }
res = res.substring(0, res.length() - 1);
return res;
}
} string char_and_num_return(string text_source) {
// write code here
vector<string> strs;
vector<long long> ints;
string str = "";
const int intFlag = 0, strFlag = 1, nan = 2;
int flag = nan;
for (char& ch : text_source) {
if (ch ==' ') {
if (flag == intFlag) ints.emplace_back(stoll(str));
else if(flag==strFlag) strs.emplace_back(str);
flag = nan;
str.clear();
continue;
}
else if (ch >= '0' && ch <= '9') {
flag = intFlag;
}
else {
flag = strFlag;
}
str += ch;
}
if (flag == intFlag) ints.emplace_back(stoll(str));
else if (flag == strFlag) strs.emplace_back(str);
sort(ints.begin(), ints.end());
string ans ="";
if (!strs.empty()) {
ans = strs[0];
int n = strs.size();
for (int i = 1; i < n;++i) {
ans += ' ';
ans += strs[i];
}
}
if (!ints.empty()) {
if (!ans.empty()) ans += ' ';
int n = ints.size();
for (int i = 0; i < n; ++i) {
ans += to_string(ints[i]);
if (i != n - 1) ans += ' ';
}
}
return ans;
} import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param text_source string字符串 原始输入
* @return string字符串
*/
public String char_and_num_return (String text_source) {
//先把String转成String数组
String[] s = text_source.split(" ");
Arrays.sort(s, (a, b) -> {
if(isString(a) && isString(b)) {
return 0;
} else if(isString(a) && !isString(b)) {
return -1;
} else if(!isString(a) && isString(b)) {
return 1;
} else {
return (int)(Long.valueOf(a) - Long.valueOf(b));
}
});
StringBuilder res = new StringBuilder();
for(String item : s) {
res.append(item).append(" ");
}
return res.toString().trim();
}
boolean isString(String c) {
return c.charAt(0) > 57;
}
} class Solution:
def char_and_num_return(self , text_source ):
text_source = text_source.split(' ')
point = 0
for i in range(len(text_source)):
if not text_source[i].isdigit():
text_source[point],text_source[i] = text_source[i],text_source[point]
point+=1
else:
text_source[i] = int(text_source[i])
text_source[point:] = [str(s) for s in sorted(text_source[point:])]
return ' '.join(text_source) import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param text_source string字符串 原始输入
* @return string字符串
*/
public String char_and_num_return (String text_source) {
// write code here
if (text_source == null || text_source.length() == 0) return "";
String[] strs = text_source.split(" ");
int n = strs.length;
StringBuilder sb = new StringBuilder();
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (Character.isDigit(strs[i].charAt(0))) {
list.add(Long.parseLong(strs[i]));
} else {
sb.append(strs[i]);
sb.append(" ");
}
}
int size = list.size();
if (size == 0) {
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
} else {
Collections.sort(list);
for (int i = 0; i < size; i++) {
sb.append(list.get(i));
if (i < (size - 1)) sb.append(" ");
}
}
return sb.toString();
}
} import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param text_source string字符串 原始输入
* @return string字符串
*/
public static String char_and_num_return (String text_source) {
if (text_source.equals("")) {
return "";
}
String[] str = text_source.split(" ");
StringBuilder sb = new StringBuilder();
PriorityQueue<Long> queue = new PriorityQueue<>();
for (int i = 0; i < str.length; i++) {
if (str[i].charAt(0) > 89) {
sb.append(str[i]).append(" ");
} else {
queue.add(Long.parseLong(str[i]));
}
}
while (!queue.isEmpty()) {
sb.append(queue.peek()).append(" ");
queue.poll();
}
text_source = sb.substring(0, sb.length() - 1);
return text_source;
}
} import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param text_source string字符串 原始输入
* @return string字符串
*/
public String char_and_num_return (String text_source) {
// write code here
//双指针将字母换到前面
if(text_source==null||"".equals(text_source)) return "";
String[] strs=text_source.split(" ");
int p=0;
for(int i=0;i<strs.length;i++){
if(!isNum(strs[i])){
swap(strs,p,i);
p++;
}
}
//对于后面的数字,采用快速排序
quickSort(strs,p,strs.length-1);
StringBuilder builder =new StringBuilder();
for(int i=0;i<strs.length;i++){
builder.append(strs[i]);
if(i!=strs.length-1) builder.append(" ");
}
return builder.toString();
}
//判断是否是数字
public boolean isNum(String str){
char c=str.charAt(0);
return c>='0'&&c<='9';
}
//swap
public void swap(String[] strs, int i, int j){
String temp=strs[i];
strs[i]=strs[j];
strs[j]=temp;
}
//快排递归部分
public void quickSort(String[] strs, int i, int j){
if(i>=j) return;
int mid=partition(strs,i,j);
quickSort(strs,i,mid-1);
quickSort(strs,mid+1,j);
}
//partition
public int partition(String[] strs, int left, int right){
String pivot=strs[left];
int i=left,j=right;
while(i<j){
while(i<j&&compareStr(strs[j],pivot)>=0){
j--;
}
while(i<j&&compareStr(strs[i],pivot)<=0){
i++;
}
swap(strs,left,i);
}
return i;
}
//字符串数字比较规则
public int compareStr(String str1, String str2){
long a =Long.parseLong(str1);
long b =Long.parseLong(str2);
return a>b?1:(a==b?0:-1);
}
} package main
import (
"strings"
"strconv"
"sort"
)
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param text_source string字符串 原始输入
* @return string字符串
*/
func char_and_num_return( text_source string ) string {
// write code here
if len(text_source) == 0 {
return text_source
}
textArr := strings.Split(text_source, " ")
var charText string
nums, num2Char := []int{}, make(map[int]string)
for _, text := range textArr {
if rune(text[0]) >= '0' && rune(text[0]) <= '9' {
num, _ := strconv.Atoi(text)
nums, num2Char[num] = append(nums, num), text
} else {
if len(charText) == 0 {
charText = charText + text
} else {
charText = charText + " " + text
}
}
}
sort.Ints(nums)
for _, num := range nums {
numStr, _ := num2Char[num]
if len(charText) == 0 {
charText = numStr
} else {
charText = charText + " " + numStr
}
}
return charText
} class Solution: def char_and_num_return(self , text_source ): # write code here data = text_source.split() num = [] word = [] for i in data: if i.isalpha()==0: num.append(int(i)) else: word.append(i) num.sort() for i in num: word.append(str(i)) words = ' '.join(word) return words
class Solution:
def char_and_num_return(self , text_source ):
# write code here
text_list = text_source.split(' ')
num_list = []
alpha_list = []
for each in text_list:
if each.isdigit():
num_list.append(int(each))
else:
alpha_list.append(each)
alpha_list += [str(x) for x in sorted(num_list)]
result = ''
for i in range(len(alpha_list)):
if i == 0:
result += alpha_list[i]
else:
result += ' '
result += alpha_list[i]
return result c++ 直接stringstream流处理
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param text_source string字符串 原始输入
* @return string字符串
*/
using LL = long long;
static bool cmp(string s1, string s2) {
LL a = stoll(s1), b = stoll(s2);
return a < b;
}
string char_and_num_return(string str) {
// write code here
stringstream sin(str);
string s;
vector alp, nums;
while (sin >> s) {
if (isdigit(s[0]))
nums.push_back(s);
else alp.push_back(s);
}
string res = "";
sort(nums.begin(), nums.end(), cmp);
bool flag = false;
for (int i = 0; i < alp.size(); i ++ ) {
if (!flag) {
flag = true;
res += alp[i];
} else res += " " + alp[i];
}
for (int i = 0; i < nums.size(); i ++ ) {
if (!flag) {
flag = true;
res += nums[i];
} else res += " " + nums[i];
}
return res;
}
};
#python实现
class Solution:
def char_and_num_return(self , text_source ):
text_source = text_source.split(" ")
number = []
char = []
for i in range(len(text_source)):
if text_source[i].isdigit():
number.append(int(text_source[i]))
else:
char.append(text_source[i])
number.sort()
for i in range(len(number)):
char.append(str(number[i]))
result = ' '.join(char)
return result class Solution: def char_and_num_return(self , text_source ): str_n=[] str_s=[] i=0 while i<len(text_source): if text_source[i].isdigit(): start = i while i+1<len(text_source) and text_source[i+1].isdigit(): i = i+1 str_n.append(int(text_source[start:i+1])) if text_source[i].isalpha(): start = i while i + 1 < len(text_source) and text_source[i + 1].isalpha(): i = i + 1 str_s.append(text_source[start:i + 1]) i=i+1 str_n.sort() str1="" for i in str_n: str_s.append(str(i)) str1 = ' '.join(str_s) return str1
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param text_source string字符串 原始输入
# @return string字符串
#
class Solution:
def char_and_num_return(self , text_source ):
# write code here
words = text_source.split()
numbers = []
alpha = []
for word in words:
if ord(word[0])>ord('9'):
alpha.append(word)
else:
numbers.append(int(word))
numbers = sorted(numbers)
numbers = list(map(str, numbers))
res = alpha + numbers
res = ' '.join(res)
return res function char_and_num_return( text_source ) {
// write code here
// write code here
let arr = text_source.split(' ')
let n = arr.length
let l = 0,r = 0
for(;r < n;r++){
if(isNaN(parseInt(arr[r]))){
let temp = arr[l]
arr[l] = arr[r]
arr[r] = temp
l++
}
}
console.log(arr)
return arr.sort((a,b)=>a-b).join(' ')
}