中级农民
积分 103
大米 颗
鳄梨 个
水井 尺
蓝莓 颗
萝卜 根
小米 粒
学分 个
注册时间 2018-3-22
最后登录 1970-1-1
2022(7-9月) 码农类General 硕士 全职 @华为Flexport - 内推 - 技术电面 视频面试 | Other | 应届毕业生
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
目前进行Coding 1面
题目跟地理一样
地里的generate random sentence
this is a sentence it is a good one and it is also bad
5
. From 1point 3acres bbs
is not a sentence it. 1point 3acres
输入:一个句子
一个新组装句子长度
输出:组装的新句子
规则:按照随机选择一个单词作为句子头单词,然后在句子中寻找头单词后续节点,添加到新句子中
方案:将句子按照空格拆分,然后进行构建map,并将后续的单词作为value。/*
* Click `Run` to execute the snippet below!
this is a sentence it is a good one and it is also bad
5
is not a sentence it
*/. 1point 3 acres
import java.io.*;
import java.util.*;
public class ConstructNewWords {
public String getNewWords(String words, int n){
if(words==null){.--
return "";. check 1point3acres for more.
}
StringBuilder ans = new StringBuilder();
String[] wordsString = words.split(" ");
Map<String, Set<String>> wordsMap = new HashMap<>();
int length = wordsString.length;
// 构建map
for(int i=0;i<length-1;i++){
String tmpKey = wordsString[i];
String tmpValue = wordsString[i+1];
if(!wordsMap.containsKey(tmpKey)){.
Set<String> wordSet = new HashSet<>();. ----
wordSet.add(tmpValue);. ----
wordsMap.put(tmpKey, wordSet);
}else{
wordsMap.get(tmpKey).add(tmpValue);
}
}
if(!wordsMap.containsKey(wordsString[length-1])){
Set<String> wordSet = new HashSet<>();. .и
wordSet.add(wordsString[0]);
wordsMap.put(wordsString[length-1], wordSet);.1point3acres
}else{
wordsMap.get(wordsString[length-1]).add(wordsString[0]);. Waral dи,
}
int randomI = new Random().nextInt(length-1);
. From 1point 3acres bbs String randomWord = wordsString[randomI];
while(n>0){. From 1point 3acres bbs
ans.append(randomWord).append(" ");. check 1point3acres for more.
Set<String> wordTmpSet = wordsMap.get(randomWord);
int tmpLen = wordTmpSet.size();
randomI = new Random().nextInt(tmpLen);. 1point3acres
String[] tm = new String[tmpLen];
int indx = 0;
for (String v:wordTmpSet){
. .и tm[indx] = v;
indx++;
}
randomWord = tm[randomI];
n--;
}
return ans.toString();
}
public static void main(String[] args) {
String words = "this is a sentence it is a good one and it is also bad";
int n = 5;. check 1point3acres for more.
String ans = new ConstructNewWords().getNewWords(words,n);. ----
System.out.println(ans);
}. 1point 3 acres
}.
复制代码
上一篇:
字节本地生活后端面经 下一篇:
上海AWS挂经