我在某个门户网站上进行测试。问题如下:
我们将一个句子定义为一系列空格分隔的单词,以大写字母开头,后跟小写字母和空格,以句点结束(即,它满足正则表达式^ [AZ] [az] * 。$)。我们想要重新排列句子中的单词,以满足以下条件:
- 每个单词按长度排序,升序。
- 相同长度的单词必须以与原始句子相同的顺序出现。
- 重新排列的句子必须格式化为满足正则表达式^ [A-Z] [a-z] *。$。
例如,考虑句子猫和帽子。首先,按照长度排序,保持关系的原始顺序:[和,猫,帽子]。现在重新组合句子,应用格式:和猫帽子。
功能描述
在下面的编辑器中完成功能安排。该函数必须返回如所述排列的正确形式的句子。
arrange具有以下参数:
sentence: a well formed sentence string
约束
2< = |句子| < 10 5 句子满足正则表达式^ [A-Z] [a-z] *。$。
我的解决方案如下:
function arrange(sentence) {
sentence = sentence.toLowerCase().substring(0,sentence.length-1).trim();
let sortedTokens = sentence.split(" ").sort((a, b) =>(a.length - b.length));
let joined = sortedTokens.join(" ") + ".";
return joined[0].toUpperCase()+ joined.substring(1);
}
不幸的是,它没有通过所有测试(我想我错过了一些极端情况)如下:
由于测试用例输入被禁止访问,我无法找到原因?
答案 0 :(得分:1)
Array.prototype.sort在相等的情况下不稳定
由于user3707125建议Array.prototype.sort是不稳定的,它给出了意想不到的顺序,所以我使用了以下它并且它起作用了:
function arrange(sentence) {
Array.prototype.sort = function(cmp) {
cmp = !!cmp ? cmp : (a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
let stabilizedThis = this.map((el, index) => [el, index]);
let stableCmp = (a, b) => {
let order = cmp(a[0], b[0]);
if (order != 0) return order;
return a[1] - b[1];
}
stabilizedThis.sort(stableCmp);
for (let i=0; i<this.length; i++) {
this[i] = stabilizedThis[i][0];
}
return this;
}
sentence = sentence.toLowerCase().substring(0,sentence.length-1).trim();
let sortedTokens = sentence.split(" ").sort((a, b) =>(a.length - b.length));
let joined = sortedTokens.join(" ") + ".";
return joined[0].toUpperCase()+ joined.substring(1);
}
答案 1 :(得分:1)
使用LinkedHashMap解决此问题!
Input: "The lines are printed in reverse order."
String sentence = "The lines are printed in reverse order.";
StringBuilder sb = new StringBuilder();
String input = sentence.substring(0, sentence.length()-1);
LinkedHashMap<String, Integer> hm = new LinkedHashMap<String, Integer>();
for(String word : input.toLowerCase().split(" ")){
hm.put(word, word.length());
}
hm.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue())
.forEach(e->{
sb.append(e.getKey() + " ");
});
String result = sb.substring(0, 1).toUpperCase() + sb.substring(1).trim() + ".";
return result;
在返回值之前,Use可以使用result.matches(“ ^ [A-Z] [a-z] *。$)”)!
Output: "In the are lines order printed reverse."
答案 2 :(得分:1)
使用树形图将长度视为关键。然后遍历每个单词并将它们相应地放在适当的位置。
function arrange(sentence) {
sentence = sentence.substring(0, sentence.length()-1);
sentence = sentence.toLowerCase();
String[] split = sentence.split(" ");
StringBuilder solution = new StringBuilder();
Map<Integer, List<String>> map = new TreeMap<>();
Arrays.stream(split).forEach(s -> {
int l = s.length();
map.putIfAbsent(l, new ArrayList<>());
map.get(l).add(s);
});
map.forEach((key, value) -> value.forEach(s -> solution.append(s).append(" ")));
String ans = solution.toString().trim();
ans = ans.substring(0,1).toUpperCase() + ans.substring(1) + ".";
return ans;
}
答案 3 :(得分:1)
public static String arrange(String sentence)
{
sentence=sentence.replace(".", " ");
StringBuilder requiredSentence=new StringBuilder();
String[] words=sentence.split(" ");
List wordsList=new LinkedList<String>(Arrays.asList(words));
while(wordsList.size()!=0)
{
int leatSizedWordIndex=0;
for(int x=0;x<wordsList.size();x++)
{
if(wordsList.get(x).toString().length()<wordsList.get(leatSizedWordIndex).toString().length())
{
leatSizedWordIndex=x;
}
}
requiredSentence.append(wordsList.get(leatSizedWordIndex).toString().toLowerCase()+" ");
wordsList.remove(leatSizedWordIndex);
}
requiredSentence =new StringBuilder(requiredSentence.toString().substring(0, 1).toUpperCase() + requiredSentence.toString().substring(1));
requiredSentence=new StringBuilder( requiredSentence.substring(0,requiredSentence.length()-1));
return requiredSentence+".";
}
答案 4 :(得分:1)
可以通过将每个单词及其相对位置存储在二维数组中来轻松完成此操作。按单词长度或在平局情况下(相同长度的单词)对数组进行排序,按相对位置(原始顺序)对数组进行排序即可得到答案。
function arrange(sentence){
sentence = sentence.toLowerCase().substring(0, sentence.length - 1).trim();
let tokens = sentence.split(" ");
// In two dimension array, keep the words with its original index
let tokensWithIndex = tokens.map((token, index) => [token, index]);
// Sort tokens (words) by length, if similar length tokens (words) are found, then sort it by its original index value
tokensWithIndex.sort((a, b) => a[0].length - b[0].length || a[1] - b[1]);
// Extract sorted tokens (words) to new one dimension array
let sortedTokens = tokensWithIndex.map(x => x[0]);
let joinedTokens = sortedTokens.join(" ") + ".";
return joinedTokens[0].toUpperCase() + joinedTokens.substring(1);
}