每日面试题
计算一个结构体大小
编译器会以结构体中最大的成员为基准进行字节填充。例如在64位系统中
struct s1 {
int a; //4B
char b; //1B
int c; //4B
long d; //8B
char e; //1B
};
那么就会以8B为基准进行对齐,最终的结构体大小也一定是8B的整数倍,即
占用32字节。(在32位系统中long占4B,64位系统中long占8B)。
字节填充对齐的目的是为了让计算机快速读取,用空间交换速度。
结构体成员数组大小
struct st {
int a; // 假设为4字节(32位系统)或8字节(64位系统)
int b; // 同上
char c[0]; // 在计算结构体大小时,这通常不被考虑
};
c[0]为柔性数组,不占用字节,因此sizeof(st)=8;
struct book{
char name[5];
float price;
}book[2];
所以sizeof(book) = 12;
因为book[2]中包含两个struct book的数组,因此sizeof(book[2])=24;
每日算法
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
class Solution {
public:
string compressString(string S) {
string res ="";
char pre=S[0];
int c=1;
if(S.empty()) return res;
for(int i=1;i<S.size();i++){
if(pre != S[i]){
res+=pre;
res+=to_string(c);
pre=S[i];
c=1;
}else{
c++;
}
}
res+=pre;
res+=to_string(c);
if(res.size()>=S.size()) return S;
else return res;
}
};