首页 > 试题广场 >

重排字符串和数字

[编程题]重排字符串和数字
  • 热度指数:2610 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
对于给定的一个包含连续字母、连续数字及空格的字符串(不会出现字母和数字连在一起出现),实现字母部分按出现顺序排列而数字按照从小到达顺序排在最后一个字母的后面。

数据范围: 字符串长度满足
进阶:空间复杂度 , 时间复杂度
示例1

输入

"xb 1 cc 5 dd 10 ee 2"

输出

"xb cc dd ee 1 2 5 10"
示例2

输入

""

输出

""
遍历字符串中的所有item,将字母item直接追加到StringBuilder中,而数字item追加到一个按数字大小升序排列的优先队列中。遍历完成后再将优先队列中的item按顺序全部追加到StringBuilder中即可。
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();
    }
}
编辑于 2022-03-09 21:11:51 回复(8)
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)

发表于 2022-03-05 12:05:10 回复(0)
//golang
func char_and_num_return( text_source string ) string {
    array := strings.Split(text_source ," ")
    s1 := []string{}
    s2 := []int{}
    for i := 0 ; i < len(array); i++{
        num ,err := strconv.Atoi(array[i])
        if err != nil{
            s1 = append(s1, array[i])
        }else{
            s2 = append(s2, num)
        }

    }
    sort.Ints(s2)
    for i := 0; i < len(s2); i++ {
        s1 = append(s1, strconv.Itoa(s2[i]))
    }
    //数组转化为用空格分隔字符串
    result := strings.Join(s1," ")
    return result
}
发表于 2021-08-27 15:40:00 回复(0)
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();
    }

发表于 2021-08-27 10:36:03 回复(0)
//*.调用 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;
    }
}

发表于 2022-03-14 18:12:30 回复(0)
//C++
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;
    }


发表于 2021-08-31 20:13:15 回复(1)
根据字母和数字指定不同的排序规则,利用Arrays.sort()排序
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;
    }
}


发表于 2021-12-12 22:34:45 回复(0)
将数字加入list中,排序后拼接到字符后面。
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();
    }
}

发表于 2022-09-01 14:47:04 回复(0)
C++更通用一点不转longlong的方法
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param text_source string字符串 原始输入
     * @return string字符串
     */
    string char_and_num_return(string text_source) {
        // write code here
        stringstream ss(text_source);
        string temp;
        vector<string> num, letter;
        while (ss >> temp) {
            if (isdigit(temp[0])) {
                num.push_back(temp);
            }
            else {
                letter.push_back(temp);
            }
        }
        if (num.size() == 0 && letter.size() == 0) {
            return "";
        }
        sort(num.begin(), num.end(), [](string& u, string& v) {
            if (u.size() > v.size()) {
                return false;
            }
            else if (u.size() < v.size()){
                return true;
            }
            return u < v ? true : false;
        });
        string ans;
        for (string& str : letter) {
            ans += str;
            ans += ' ';
        }
        for (string& str : num) {
            ans += str;
            ans += ' ';
        }
        ans.pop_back();
        return ans;
    }
};
发表于 2022-08-05 16:45:02 回复(0)
利用双指针加快排,时间复杂度O(n)+O(m logm), 其中n+m为数组长度
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);
    }

}

发表于 2022-07-26 12:08:30 回复(0)
golang 版本
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
}

发表于 2022-04-04 23:09:00 回复(0)
无脑python
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


发表于 2022-04-04 16:50:51 回复(0)
function char_and_num_return( text_source ) {
    let arr = text_source.split(' ')
    let numList = arr.filter(item => !isNaN(item))
    let strList = arr.filter(item => isNaN(item))
    numList = numList.sort((a,b) => a-b);
    const result = strList.concat(numList).join(" ")
    return result
}
发表于 2022-03-07 09:37:41 回复(0)
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

发表于 2021-11-02 15:19:00 回复(0)

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;
    }
};
发表于 2021-09-24 11:40:58 回复(0)
#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

发表于 2021-09-07 14:01:26 回复(0)
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

发表于 2021-09-06 19:01:07 回复(0)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @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

发表于 2021-09-05 20:48:46 回复(0)
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(' ')
}

lc 移动0 然后再排序
发表于 2021-08-27 00:41:51 回复(0)
```
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param text_source string字符串 原始输入
     * @return string字符串
     */
    string char_and_num_return(string text_source) {
        string ans;
        vector<long long> v;
        for(int i = 0;i < text_source.size();){
            int j = i;
            if(isalpha(text_source[i])){
                while(j < text_source.size() && isalpha(text_source[j])) j ++;
                ans += " " + text_source.substr(i,j - i);
                i = j + 1;
            }else{
                long long num = 0;
                while(text_source[j] >= '0' && text_source[j] <= '9'){
                    num = num * 10 + text_source[j] - '0';
                    j ++;
                }
                i = j + 1;
                v.push_back(num);
            }
        }
        sort(v.begin(),v.end());
        for(auto i : v) ans += " " + to_string(i);
        return ans.substr(1);
    }
};

```
发表于 2021-08-26 21:50:30 回复(0)