【算法题】比较两个版本号的大小(js)



js 复制代码
const lines = ["5.2", "5.1a"];
const lines1 = ["5.6.1", "5.6.2a"];
const lines2 = ["5.6.8.a", "5.6.8.0a"];
const lines3 = ["5.06.08.a", "5.6.8.0a"];
const lines4 = ["5", "5.0.0.0"];
function solution(lines) {
  const [verson1, version2] = lines;
  if (!isValid(verson1) || !isValid(version2)) return 0;
  const str1 = verson1.replace(/[\.0]/g, "");
  const str2 = version2.replace(/[\.0]/g, "");
  return parseInt(str1) !== parseInt(str2)
    ? parseInt(str1) > parseInt(str2)
      ? 1
      : -1
    : 0;
  console.log(str1, str2);
  function isValid(ver) {
    if (/[^0-9a-zA-Z.]/.test(ver)) return false;
    const arr = ver.split(".");
    if (arr.length < 1) return false;
    return true;
  }
}

console.log(solution(lines));
/* 
5.2
5.1a
=> 1

5.6.1
5.6.2a
=>
-1

5.6.8.a
5.6.8.0a
=>
0

const lines3 = ["5.06.08.a", "5.6.8.0a"];  预计 0
const lines4 = ["5", "5.0.0.0"];    预计 0
 */
相关推荐
李少兄28 分钟前
深入理解 CSS :not() 否定伪类选择器
前端·css
2301_7890156231 分钟前
C++:二叉搜索树
c语言·开发语言·数据结构·c++·算法·排序算法
程序员码歌7 小时前
短思考第261天,浪费时间的十个低效行为,看看你中了几个?
前端·ai编程
Swift社区8 小时前
React Navigation 生命周期完整心智模型
前端·react.js·前端框架
若梦plus8 小时前
从微信公众号&小程序的SDK剖析JSBridge
前端
leiming68 小时前
C++ vector容器
开发语言·c++·算法
用泥种荷花8 小时前
Python环境安装
前端
Light608 小时前
性能提升 60%:前端性能优化终极指南
前端·性能优化·图片压缩·渲染优化·按需拆包·边缘缓存·ai 自动化
Jimmy9 小时前
年终总结 - 2025 故事集
前端·后端·程序员