假定屏幕的像素宽度为screenwidth,写一个函数,计算一个字符串需要分成几行显示,要求:
1。每行应尽可能多的显示字符,但不能有字符部分或完全显示屏幕外,超过部分的字符换下一行显示
2.每个字符的像素宽度不一样,用int.GetcharWidth(char c)获得每个字符的像素宽度

解决方案 »

  1.   

    这个字符串的内容是要顺序显示还是可以打乱顺序显示?如果是顺序显示那很简单,基本不用什么算法,搞个循环
     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)
      

  2.   

    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;
             }
                      
    }
    请问下,show current char in the new line;这句话就能让多余的字符换行??如果要显示多行怎么办?
      

  3.   

    dash_running
    这位朋友太风趣了.
      

  4.   

    java是初学,我就是想知道怎么才能显示多行啊,我也知道你这种思路,就是不会写代码