顺丰科技历年秋招笔试真题
如需获取完整资料,请点击下方链接领取《2024校招笔试真题秘籍》(实时更新中)
不收费,3人组团即可一块免费领取!限量免费10000个名额
手机端点击免费领取:https://www.nowcoder.com/link/campus_xzbs2
电脑端请扫码领取:
1、单词数组左右对齐
【题目描述】给定一个单词数组和一个长度maxWidth,重新排版单词,使其成为每行恰好有maxWidth个字符,且左右两端对齐的文本。
你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格' '填充,使得每行恰好有maxWidth个字符。
要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。
文本的最后一行应为左对齐,且单词之间不插入额外的空格。
说明:
单词是指由非空格字符组成的字符序列。每个单词的长度大于 0,小于等于maxWidth。输入单词数组words至少包含一个单词。
输入样例:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
输出样例:
'What must be'
'acknowledgment '
'shall be '
解释:
注意最后一行的格式应为 "shall be " 而不是 "shall be",
因为最后一行应为左对齐,而不是左右两端对齐。
第二行同样为左对齐,这是因为这行只包含一个单词。
难度:4级
时间限制:C/C++语言1000MS;其他语言3000MS
内存限制:C/C++语言65536KB;其他语言589824KB
输入描述:
一个单词数组和一个长度 maxWidth
输出描述:
重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本
输入样例:
Today,I,consider,myself,the,luckiest,man,on,the,face,of,the,earth.
16
输出样例:
'Today I consider'
'myself the'
'luckiest man on'
'the face of the'
'earth. '
提示:
public class Main {
public static void main(String[] args) {
String str1 = "What,must,be,acknowledgment,shall,be";
String str2 = "16";
List result = fullJustify(str1.split(","), Integer.valueOf(str2));
for(String str : result){
System.out.println("'"+str+"'");
}
}
/**
* TODO 算法实现
* @param words 单词数组
* @param maxWidth 每行长度
* @return 结果集合
*/
public static List fullJustify(String[] words, int maxWidth) {
}
}
【解题思路】
按题意模拟。
先解析出所有词,贪心的往每行中放尽量多的词,如果放不下,稍加计算即可得出单词间的空格数。
【参考代码】
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
char s[N];
int w;
int main() {
scanf("%s%d", s, &w);
int n = strlen(s);
s[n++] = ',';
vector<string> words;
string word = "";
for(int i = 0; i < n; ++i) {
if(s[i] == ',') {
words.push_back(word);
word = "";
}else {
word += s[i];
}
}
vector<string> line;
int width = -1;
int space = w;
for(string word : words) {
if(width + word.size() + 1 > w) {
int m = line.size();
if(m == 1) {
line[0] += ' ';
printf("\'%-*s\'\n", w, line[0].c_str());
}else {
int gap = space / (m - 1);
int extra = space % (m - 1);
putchar('\'');
for(int i = 0; i < m; ++i)
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
本专刊由牛客官方团队打造,主要讲解名企校招技术岗位的笔试题,内容中包含多个名企的笔试真题,附有题目思路及参考代码
