如何从一个字符串中找到最小的字符串。换句话说,找到最小的字符串,使其可以连接多次以获得大字符串。
输入rbr
输出rb
(我的函数工作正常)
另一个例子
输入 bcdbcdbcdbcd
输出:bcd
(我的函数工作正常)
我试过这样的。
function getSmallestString(s){
let i= 0;
let tem = '';
while(true){
let mid = s.length/2;
let tem = s.substring(0,mid);
if(tem + tem == s){
s= tem
}else {
return s;
}
}
}
console.log('bcdbcdbcdbcd')
https://jsbin.com/liracurala/1/edit?html,js,output
这里我的案例失败了
function getSmallestString(s){
let i= 0;
let tem = '';
while(true){
let mid = Math.floor(s.length/2);
let tem = s.substring(0,mid);
if(tem + tem == s){
s= tem
}else {
return s;
}
}
}
console.log(getSmallestString('ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo'))
预期输出是o
在这种情况下,每个答案都失败了 lrbb
预期输出 lrbb
最佳答案
function getSmallestString(str) {
var current = "";
for(var i = 0, len = str.length; i < len; ++i) {
current += str[i];
if(str.replace(new RegExp(current,"g"),"") == "") return current
}
}
关于javascript - 如何从大字符串中获取最小字符串(从小字符串连接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63454486/