將n進位的數組壓縮成字串(0-9 a-z)同時解壓,0-9a-z

來源:互聯網
上載者:User

將n進位的數組壓縮成字串(0-9 a-z)同時解壓,0-9a-z

此類題目要明確兩點:

1. 打表:用數組下標索引字元,同時注意如果從字元對應回數字: 

int index = (str[i] >= '0' && str[i] <= '9') ? (str[i]-'0'-radix):(str[i]-'a'-radix + 10);

2. 注意低位在前還是高位在前,如果先來的是 低位*radix^i 即可。

3. 統計每幾個radix進位數組成一位,利用bits來表示。。。


這破題主要是麻煩。。。


#include <assert.h>#include <algorithm>#include <vector>using namespace std;const int radix = 4;string base = "";string compress(const vector<int>& arr) {  string res = "";    int i, j, size = arr.size(), left, bits;    for (i = 1, j = 0; i*radix + radix < 36; i *= radix, ++j);  bits = j;  left = size - size / bits * bits;  size = size / bits * bits;  for (char ch = '0'; ch <= '9'; ++ch)    base.push_back(ch);  for (char ch = 'a'; ch <= 'z'; ++ch)    base.push_back(ch);  for (i = 0; i < size; i += bits) {    int index = 0, t = 1;    for (j = 0; j < bits; ++j) {      index = index + arr[i+j]*t;      t *= radix;    }               res.push_back(base[radix+index]);  }  for (i = 0; i < left; ++i)    res.push_back(arr[size+i]+'0');  return res; }vector<int> depress(const string& str) {  int len = str.length(), i = 0, j, bits;  for (i = 1, j = 0; i*radix + radix< 36; i *= radix, ++j);  bits = j;  vector<int> res;  for (i = 0; i < len; ++i) {    if (str[i]-'0' >= 0 && str[i]-'0' < radix)       res.push_back(str[i]-'0');    else {      int index = (str[i] >= '0' && str[i] <= '9') ? (str[i]-'0'-radix):(str[i]-'a'-radix + 10);            for (j = 0; j < bits; ++j) {        res.push_back(index%radix);        index = index/radix;      }    }  }  return res;} int main() {  int arr[] = {0,1,2,2,2,2,1,1,1,2,0,0,0,0,0,1};  vector<int> vec(arr, arr+sizeof(arr) / sizeof(int));  string str = compress(vec);  vector<int> res = depress(str);  return 0;}




C# 把字串按照A-Z的順序排列,儲存在一個數組中先增加一個新的字串,並保證該數組是有序的

數組本身是無序的——儲存順序。所以沒有必須保數組儲存進行排序。可以使用資料的排序函資料sort或者使用lambda運算式進行排序後取值即可,不必在意數組的順序——除非你願意再開闢一個數組空間進行儲存——這對記憶體上是有要求的。
 
C語言,怎判斷一個字元數組中元素是否包含除字母(a-z,A-Z)與數字(0-9)以外的東西

可以的,利用迴圈。
下面只判斷是不是全為字母或數字,如果不是則列印其位置和符號。
/* Note:Your choice is C IDE */
#include "stdio.h"
void main()
{

int i,c=0;
char a[6];
scanf("%s",&a);
for(i=0; i<5 ;i++)
{
if(a[i] <= 'z'&&a[i] >='a'||a[i] <= 'Z' && a[i] >='A'||a[i]>=48 && a[i]<=57)
{
c++;
}
else
printf("第%d個位置:%c\n",i+1,a[i]);

}

if(c==5)
{
printf("全為字母或數字\n");
}

}
不懂的地方可以追問
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.