假定屏幕的像素宽度为screenwidth,写一个函数,计算一个字符串需要分成几行显示,要求:
1。每行应尽可能多的显示字符,但不能有字符部分或完全显示屏幕外,超过部分的字符换下一行显示
2.每个字符的像素宽度不一样,用int.GetcharWidth(char c)获得每个字符的像素宽度
1。每行应尽可能多的显示字符,但不能有字符部分或完全显示屏幕外,超过部分的字符换下一行显示
2.每个字符的像素宽度不一样,用int.GetcharWidth(char c)获得每个字符的像素宽度
调试欢乐多
while there's next char{
read next char to current char;
if screenwidth < GetcharWith(current char){
output error, because the screen is too narrow for one char;
break;
}
if current char's width > the remain width of current line{
show current char in the new line;
}
}
时间复杂度是o(n)如果字符的顺序可以打乱,就麻烦点,不过有现成算法,
用贪心法,每次取最长的一个字符显示在当前行就可以了
每次取最长的,n个字符就需要 n-1 + n-2 + n-3 +...+ n-(n-1) = n(n-1)-(n-1)(n)/2 次比较
时间复杂度是o(n^2)
read next char to current char;
if screenwidth < GetcharWith(current char){
output error, because the screen is too narrow for one char;
break;
}
if current char's width > the remain width of current line{
show current char in the new line;
}
}
请问下,show current char in the new line;这句话就能让多余的字符换行??如果要显示多行怎么办?
这位朋友太风趣了.