Reorganize String 重构字符串--每日一题

昨天在Google hackathon中有一个模拟面试的环节,面试官问了这样一道题–
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result.
给一个字符串,重构这个字符串,使得相同的字符不会相邻。

首先学会提问:
任何模糊不清楚的问题都要跟面试官确定清楚,比如:
一定有可行解吗?如果无法做到,那么返回什么。
这个字符串由多少字符组成,是字母还是ASCII码还是什么。
这个字符串长度是多少等等。

本题解
当时现场我的想法是把字符串中字符按照出现的个数排序,然后每次排出现次数前两个的排进新的字符串,再更新字符个数排序逐渐循环直到结束。
后来一位同学提到奇数偶数位排序,感觉挺好的,回来后自己又想了想搜了搜,有了下面的思路:
以只有字母字符为例,一共52个字符,
我们用一个52长度的vector去存储每个字符出现的次数,但是这样排序后不容易知道出现次数对应哪个字符,于是我们可以用一种巧妙的方式,vector存储(次数*100+字符对应的int),这样就可以既存储次数信息又存储字符信息。
然后按照字符出现次数排序,按照出现次数依次间隔放置,到字符串长度后再返回第一个字符。

举例:
aaabbc
排序后:
a_a_a_
ababa_
ababac

再看一个:
aabbccdeffg
排序后:
f_f_c_c_b_b
fafac_c_b_b
fafacgcebdb

代码

//
//  reorganizeString.cpp
//  Cracking-the-code
//
//  Created by mac on 2019/3/25.
//  Copyright © 2019 iris. All rights reserved.
//

#include <iostream>
#include<cstring>
#include <vector>
using namespace std;

string reorganizeString(string s) {
    vector<int> count(52, 0);
    int len = s.length();
    for(int i = 0; i < len; i++) {
        int v = (int)(s[i]-'A');
        count[v]+=100;
    }
    for(int i = 0; i < 52; i++) {
        count[i]+=i;
    }
    sort(count.begin(), count.end());
    
    int idx = 0;
    for (int i = 51; i > 0; i--) {
        int t = count[i] / 100;
        char ch = 'A' + (count[i] % 100);
        if (t > (len + 1) / 2) return "";
        if (0 == t) return s;
        while (t--) {
            if (idx >= len) idx = 1;
            s[idx] = ch;
            idx += 2;
        }
    }
    return s;
}

int main() {
    string s = "aaabbcddeeffFABg";
    cout << reorganizeString(s) << endl;
}

输出:
adababfgfceFeBdA

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值