搜狐两个编程题前端Javascript实现
第一题:简化Unix路径(100%)
Array.prototype.isEmpty = function(){ return this.length == 0; } function simplePath(path){ var s=[]; var pathDetail = path.split("/"); var result = ''; for(var i = 0 ; i < pathDetail.length ; i++){ //弹出上级目录,如果有上级目录 if(pathDetail[i] == ".."){ if(s.isEmpty()){ continue; } s.pop(); }else if(pathDetail[i] == "." || pathDetail[i].length == 0){ //不进行任何操作 continue; }else{ s.push(pathDetail[i]); } } if(s.length == 0){ return "/"; } do{ result = s.pop() + result; result = "/" + result; }while(!(s.length == 0)); return result; } var path = readline(); print(simplePath(path));
第二题:回文数组(没有跑用例,等我写完,都交卷了)
function huiwen(arr){ var sum = 0; var first,last,value; while(arr.length>1){ first = arr[0]; last = arr[arr.length-1]; value = 0; if(first != last){ if(first > last){ value = arr.pop() }else{ value = arr.shift(); } }else{ value = arr.shift(); arr.pop(); } sum += value*2; } if(arr.length==1){ sum += arr[0]; }; return sum; } var length = readline(); var arr = readline().split(' '); print(huiwen(arr)); // huiwen([1,2,3,1,2]); // 11