5B - Center Alignment【字符串】

本文介绍了一个文本居中算法的实现,该算法用于将输入的文本行居中显示,并使用特定字符进行包围。文章详细解释了如何处理不同长度的行以及如何在最小矩形内对齐文本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

B. Center Alignment
time limit per test
1 second
memory limit per test
64 megabytes
input
standard input
output
standard output

Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.

You are to implement the alignment in the shortest possible time. Good luck!

Input

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Output

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

Examples
input
This  is

Codeforces
Beta
Round
5
output
************
* This  is *
*          *
*Codeforces*
*   Beta   *
*  Round   *
*     5    *
************
input
welcome to the
Codeforces
Beta
Round 5

and
good luck
output
****************
*welcome to the*
*  Codeforces  *
*     Beta     *
*   Round 5    *
*              *
*      and     *
*  good luck   *
****************

题意:

给出一些字符串,让你用 * 号组成的最小矩形把这些字符串围起来,不足的补充空格,所有字符串中间对齐,如果出现长度的奇偶性不同,那就优先空着左边,下次再优先空着右边,输出最终处理的结果


题解:

字符串的处理,使用string 类型比较方便,这道题总体比较简单,但是有一个坑点:空行(长度为0)和所有的其他行是对齐的,处理的时候要特殊注意

错了几遍才想到这种特殊情况,自己的思维还不够细致


/*
http://blog.youkuaiyun.com/liuke19950717
*/
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
string s[10005];
int main()
{
    //freopen("shuju.txt","r",stdin);
    int cnt=0,len=0,sign=0;
    while(getline(cin,s[cnt]))
    {
        int tp=s[cnt++].length();
        len=max(len,tp);
    }
    for(int i=0;i<len+2;++i)
    {
        cout <<"*";
    }
    cout <<"\n";
    for(int i=0;i<cnt;++i)
    {
        int tplen=s[i].length();
        if((tplen&1)!=(len&1)&&tplen)//无法完全对齐
        {
            ++sign;
        }
        int tp=len-tplen;
        int ta=tp-tp/2,tb=tp-ta;//a
        if(sign&1)
        {
            swap(ta,tb);
        }
        cout <<"*";
        for(int j=0;j<ta;++j)
        {
            cout <<" ";
        }
        cout <<s[i];
        for(int j=0;j<tb;++j)
        {
            cout <<" ";
        }
        cout <<"*\n";
    }
    for(int i=0;i<len+2;++i)
    {
        cout <<"*";
    }
    cout <<"\n";
    return 0;
}



import {FootCard} from '../project2/FootCard' import {test} from '../proText/test1' import {SmallFoodCard} from '../project2/SmallFoodCard' //对FootCard的数据进行处理 @Observed class FoodItem { index: number; image: Resource; name: string; ingredient: string recommend: string sale: string price: string count: number = 0; showOp : boolean = false constructor(index:number,image:Resource,name: string, ingredient: string,recommend: string, sale: string,price: string) { this.index = index this.image = image; this.name = name; this.ingredient = ingredient this.recommend = recommend this.sale = sale this.price = price } } @Component struct VirticalBarCmp{ tabsController2: TabsController = new TabsController(); barList: string[] = ['一人套餐','特色烧烤','杂粮主食'] @State currentIndex2 :number = 0 isCurrentSelected2(item:string){ return this.barList[this.currentIndex2] === item } @Builder myTabBarItem2(item:string){//自己的item Row(){ Text(item) .fontSize(18) .fontColor(this.barList[this.currentIndex2] === item ? Color.Black : Color.Gray) .fontWeight(400) .padding(5) .backgroundColor(this.barList[this.currentIndex2] === item ?'#ffb5b5b5':'#ffeaeaea') .width('100%') .height(60) } .onClick(()=>{ this.tabsController2.changeIndex(this.barList.findIndex((i)=>item === i)) }) .margin({right:-4}) }//item2 //自己的bar @Builder myTabBar2(){ Row(){ Column({space:10}){ ForEach(this.barList,(item:string)=>{ this.myTabBarItem2(item) }) } .margin({top:3}) .width(100) .height(250) Divider() .vertical(true) .width(6) .lineCap(LineCapStyle.Round) .color(Color.Black) } .alignItems(VerticalAlign.Top) .backgroundColor('#ffeaeaea') } //购物车 @State toMoney: string = '¥0.00' @State carShow: boolean = false @State selectedFoods:FoodItem[] = [] @Provide('cardNum') //使用的子组件中只能有@compenent一个修饰符 CardNum: number = 0//小红点 // @Watch('CardNum') // onCardNumChange(){ // this.updateFoodData() // } // @Provide('clear') // clear : number = 0 clearCart(){ this.firstList2.forEach(item =>{ item.count = 0 item.showOp = false }) this.secondList2.forEach(item =>{ item.count = 0 item.showOp = false }) this.thirdList2.forEach(item =>{ item.count = 0 item.showOp = false }) this.CardNum = 0 this.toMoney = '¥0.00' this.selectedFoods = [] //创建新数组触发UI更新 this.firstList2= [...this.firstList2] this.secondList2= [...this.secondList2] this.thirdList2= [...this.thirdList2] } //更新购物车和总金额 updateFoodData(){ this.updataSelectedFoods(); this.updateTotalMoney(); } //更新总金额 updateTotalMoney(){ let total = 0 const allFoods = [...this.firstList2,...this.secondList2, ...this.thirdList2] allFoods.forEach(item =>{ if (item.count>0) { const priceStr = item.price.replace(/[^0-9.]/g, '') const price = parseFloat(priceStr) || 0 total += price * item.count } }) this.toMoney = `¥${total.toFixed(2)}` } //更新食物列表 updataSelectedFoods(){ const allFoods = [...this.firstList2,...this.secondList2, ...this.thirdList2] this.selectedFoods = allFoods.filter(item => item.count > 0) //this.updateTotalMoney() } @Builder purchaseCar(){ Column(){ Row(){ Stack(){ Image($r('app.media.ic_public_cart')) .width(45) .height(60) .objectFit(ImageFit.Cover) .margin({top:-15, left:15 }) //小红点 Text(`${this.CardNum}`) .textAlign(TextAlign.Center) .fontSize(12) .backgroundColor(Color.Red) .fontColor(Color.White) .width(15) .height(15) .borderRadius('50%') .position({x:50,y:15}) } .onClick(()=>{//点击后弹出购物车内容 if(this.CardNum != 0) this.carShow == false ? this.carShow = true : this.carShow = false }) Column({space:2}){ Text(this.toMoney) .fontSize(16) .fontWeight(FontWeight.Bold) .fontColor(Color.White) Text('预计另需配送费5¥') .fontSize(12) .fontColor(Color.Gray) } .onClick(()=>{//点击后弹出购物车内容 if(this.CardNum != 0) this.carShow == false ? this.carShow = true : this.carShow = false }) .margin({right:30,left:5}) .alignItems(HorizontalAlign.Start) Button('去结算',{type:ButtonType.Normal})//先改变按钮的默认胶囊型才能改角度 .borderRadius({ topRight: 22, bottomRight:22 }) .height(45) .fontWeight(20) .fontColor(Color.Black) .backgroundColor('#ffffcb4e') } .zIndex(2) .borderRadius(30) .position({x:40,y:615}) .justifyContent(FlexAlign.SpaceBetween) .width('80%') .height(45) .backgroundColor(Color.Black) //点击后弹出的购物车 Column(){ Row(){ Text('购物车') .fontWeight(FontWeight.Bold) .fontSize(16) //用来关闭购物车 Image($r('app.media.ic_downward')) .width(30) .height(20) .objectFit(ImageFit.Fill) .onClick(()=>{ if (this.carShow) { this.carShow = false } }) Text('清空购物车') .onClick(()=>{//点击清空 //顺便关了 if (this.carShow) { this.carShow = false } this.clearCart() }) } .padding(5) .margin(5) .width('100%') .justifyContent(FlexAlign.SpaceBetween) Divider() //里面是一个新的组件,当上面点击后会创建 //点击减号也要对应减少 //到0则destroy //小卡片区域 Column(){ if (this.selectedFoods.length === 0){ Text('购物车是空的,快去添加商品吧!( ᐛ )') .fontSize(16) .fontColor(Color.Gray) .margin({ top: 20 }) }else { ForEach(this.selectedFoods, (item: FoodItem) => { SmallFoodCard({ foodItem: item}) }, (item: FoodItem) => item.index.toString()) } } .height(300) .width('100%') .padding(10) } .zIndex(1) .backgroundColor(Color.White) .border({ width:1, color: '#ffd4d4d4' }) .width('100%') .height(500) .position({y:this.carShow == true? 165 : 680})//改这里165{y:this.carShow == true? 500 : 165} //这里不用另外两种是因为他们都是展位的,导致背后测边框无法点击,但是position打破展位关系导致我不知道怎么在 .borderRadius(20) .animation({ duration: 500 }) } } //*****************************内容数据区 @Builder defaultContentBuilder(){ Text('子默认页面') } goods1 = new FoodItem(0,$r('app.media.roujiamo'),'肉夹馍', '主料:白皮饼、猪肉','点评网友推荐','月销售653','10') goods2 = new FoodItem(1,$r('app.media.suantangyu'),'小份酸汤莜面鱼鱼', '主料:酸汤、莜面','点评网友推荐','月销售40','34.23') goods3 = new FoodItem(2,$r('app.media.zhazhupai'),'炸猪排', '主料:猪肉、面粉、面包糠','点评网友推荐','月销售999+','15') goods4 = new FoodItem(3,$r('app.media.roujiamo'),'肉夹馍套餐', '主料:白皮饼、猪肉','点评网友推荐','月销售456','25') @Provide('FoodList1') firstList2 : FoodItem[] = [this.goods1,this.goods2,this.goods3,this.goods4] @Builder firstContentBuilder2(){ //传递参数 FootCard({ FoodData: this.firstList2, }) } goods5 = new FoodItem(4,$r('app.media.kaochuan'),'小肉串', '主料:牛肉','点评网友推荐','月销售999+','0.5/串') goods6 = new FoodItem(5,$r('app.media.yangrouchuan'),'羊肉串', '主料:羊肉','点评网友推荐','月销售557','2/串') goods7 = new FoodItem(6,$r('app.media.kaozhunao'),'烤脑花', '主料:猪肉、辣椒、香菜','点评网友推荐','月销售60','15') @Provide('FoodList2') secondList2 : FoodItem[] = [this.goods5,this.goods6,this.goods7] @Builder secondContentBuilder2(){ FootCard({ FoodData: this.secondList2, }) } goods8 = new FoodItem(7,$r('app.media.xiaomizhou'),'小米粥', '主料:小米、大枣','','月销售30','5') goods9 = new FoodItem(8,$r('app.media.haixianzhou'),'海鲜粥', '主料:螃蟹、大米、小虾米','点评网友推荐','月销售50','10') goods10 = new FoodItem(9,$r('app.media.haixianchaofan'),'海鲜炒饭', '主料:大米、玉米、虾仁','点评网友推荐','月销售100','20') @Provide('FoodList3') thirdList2: FoodItem[] = [this.goods8,this.goods9,this.goods10] @Builder thirdContentBuilder2(){ FootCard({ FoodData: this.thirdList2, }) } @BuilderParam //用来处理子组件里面的参数 contentBuilder1:()=>void = this.firstContentBuilder2 @BuilderParam //用来处理子组件里面的参数 contentBuilder2:()=>void = this.secondContentBuilder2 @BuilderParam //用来处理子组件里面的参数 contentBuilder3:()=>void = this.thirdContentBuilder2 //********************************************** build() { Stack({alignContent:Alignment.TopStart}) { Tabs({ barPosition:BarPosition.Start, index:$$this.currentIndex2, controller:this.tabsController2 }) { TabContent() { this.contentBuilder1() } TabContent() { this.secondContentBuilder2() } TabContent() { this.thirdContentBuilder2() } } .scrollable(false) .width('100%') .barWidth(60) .animationDuration(0) // .backgroundColor(Color.Brown) .vertical(true) this.myTabBar2() //应该是这里下方写购物车 this.purchaseCar() } .width('100%') .onAppear(() => this.updataSelectedFoods()) } } @Entry @Component struct MTContentView { // @Builder // builder1(){ // Text('点菜的相关内容') // } build() { Row(){ VirticalBarCmp() } } } export default VirticalBarCmp 这是主页
最新发布
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值