注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
刚刚做的📞面试。
直接上题。
写个函数做字符转换。
有米的就加一些吧。的代码。
- #include <iostream>
- #include <string>
- #include <vector>
- #include <cassert>
- using namespace std;
- string translate(string &str, int start_idx, int end_idx){
- assert(end_idx >= start_idx);
- const int repeat_time = 2;
- string ret;
- if(end_idx - start_idx <= repeat_time){
- ret = str.substr(start_idx, end_idx-start_idx);
- } else {
- int repeat_number = 0;
- repeat_number = end_idx - start_idx;
- string tmp = string(1,str[start_idx]);
- ret = tmp + "#" + to_string(repeat_number);
- }
- return ret;
- }
- string coding_string(string &str){
- string ret;
- if(str.empty() || str.size() == 0){
- return ret;
- }
- if(str.size() < 3){
- return str;
- }
- int start_idx = 0, end_idx = 0, len = str.size();
- for(int i = 0; i < len; i++){
- if (i == 0){
- start_idx = i;
- } else {
- start_idx = i - 1;
- }
- end_idx = start_idx;
- while((end_idx < len) && (str[start_idx] == str[++end_idx])){
- }
- string cur_str = translate(str, start_idx, end_idx);
- ret += cur_str;
- i = end_idx;
- }
- return ret;
- }
- int main() {
- /* Enter your code here. Read input from STDIN. Print output to STDOUT */
- string str = "eddddjjwwwwwrjjjkk";
- string ret = coding_string(str);
- cout << str << endl;
- cout << ret << endl;
- return 0;
- }
复制代码
|