华为2022.08.03笔试第一题思路分享(码流等分)
题目:码流等分
二进制码流(字符串),将该码流切分成3段,每一段都得到相同的二进制值。
例如:输入为1010010,可以切分为10 10 010这三段,都表示十进制中的2。如果无法做到,则输入-1。如果码流全部为0,则视为无法做到,输出-1
示例输入:100101000001001010000100101
示例输出:100101 00000100101 0000100101
思路:
如果这3段子串相等,则每一个子串中1的个数一定是相等的。所以想到统计字符串中所有1的个数,然后除以三,如果能除得尽,则根据1的个数确定每个有效子串(以1开头,暂时忽略左侧的0)的左边界。
function spliceCode(str) { let arr = str.split(''); // 统计有多少个1 let numOfOne = str.match(/1/g, "").length; console.log(numOfOne); if (numOfOne % 3 === 0) { numOfOne = numOfOne / 3; } else { console.log(-1) return -1; } console.log(numOfOne) // 根据1的位置确定有效子串的左边界 let left1 = 0, right1 = 0, left2 = 0, right2 = 0, left3 = 0, right3 = arr.length - 1; let tempnum = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] === '1') { tempnum++; } if (tempnum === numOfOne) { left2 = i + 1; } if (tempnum === numOfOne * 2) { left3 = i + 1; } } while (arr[left1] === '0') { left1++; } // 根据第三个子串的长度来确定每个有效子串的右边界。 let newlength = right3 - left3 + 1; right1 = left1 + newlength - 1; right2 = left2 + newlength - 1; // 对比这三个子串内部是否相等 for (let k = 0; k < newlength; k++) { if (!(arr[left1 + k] === arr[left2 + k] && arr[left1 + k] === arr[left3 + k])) { return -1; } } // 如果相等,则补上有效子串前面的0(也即 以上一个子串的右边界+1为当前子串的左边界。) let substr1 = arr.slice(0, right1 + 1).join(''); let substr2 = arr.slice(right1 + 1, right2 + 1).join(''); let substr3 = arr.slice(right2 + 1).join(''); console.log(substr1 + ' ' + substr2 + ' ' + substr3); } let arr = "000100101000001001010000100101"; spliceCode(arr)
😥但是系统一直提示“超出CPU限制”。而且直接console.log也会提示超出cpu限制,有点无语……
后来就改成了python版本(代码附后面),结果也超时……
# If you need to import additional packages&nbs***bsp;classes, please import here. def func(): # please define the python3 input here. For example: a,b = map(int, input().strip().split()) # please finish the function body here. # please define the python3 output here. For example: print(). strs = "00100101000001001010000100101" arr = list(strs) # 统计有多少个1 numOfOne = strs.count('1') print(numOfOne) if (numOfOne % 3 == 0): numOfOne = numOfOne / 3 else: print(-1) return -1 print(numOfOne) left1 = 0 right1 = 0 left2 = 0 right2 = 0 left3 = 0 right3 = len(arr) - 1 tempnum = 0 for i in range(len(arr)): if (arr[i] == '1'): tempnum = tempnum+1 if (tempnum == numOfOne): left2 = i + 1 if (tempnum == numOfOne * 2): left3 = i + 1 while (arr[left1] == '0'): left1 = left1+1 newlength = right3 - left3 + 1 right1 = left1 + newlength - 1 right2 = left2 + newlength - 1 for k in range(newlength): if not(arr[left1+k] == arr[left2+k] and arr[left1+k] == arr[left3+k]): return -1 substr1 = ''.join(arr[0:right1+1]) substr2 = ''.join(arr[right1 + 1: right2 + 1]) substr3 = ''.join(arr[right2 + 1:]) print(substr1 + ' ' + substr2 + ' ' + substr3) if __name__ == "__main__": func()
写的代码可能比较拉跨,欢迎各位指正并交流。
#华为笔试#