Rentetan - Cabaran JavaScript

Susan Sarandon
Lepaskan: 2024-11-01 08:19:30
asal
808 orang telah melayarinya

String - JavaScript Challenges

Anda boleh menemui semua kod dalam siaran ini di repo Github.


Cabaran berkaitan rentetan


Adalah alfanumerik

/**
 * @param {any} char
 * @return {Boolean}
 */

function isAlphaNumeric(char) {
  return /[A-Za-z0-9]/.test(char);
}

// Usage example
console.log(isAlphaNumeric("a")); // => true
console.log(isAlphaNumeric(0)); // => true
console.log(isAlphaNumeric("!")); // => false
Salin selepas log masuk

Sarung unta <-> Kes ular

// camel case to snake case
/**
 * @param {string} str
 * @return {string}
 */
function toKebabCase(str) {
  let temp = str.replace(/[A-Z]/g, function (i) {
    return "_" + i.toLowerCase();
  });

  if (temp[0] === "_") {
    temp = temp.slice(1);
  }

  return temp;
}

// Usage example
console.log(toKebabCase("testMethod")); // => "test_method"

// snake case to camel case
/**
 * @param {string} str
 * @return {string}
 */
function toCamelCase(str) {
  return str.replace(
    /([a-z])_([a-z])/gi,
    (_, left, right) => left + right.toUpperCase()
  );
}

// Usage example
console.log(toCamelCase("test_method")); // => "testMethod"
Salin selepas log masuk

Bandingkan nombor versi

/**
 * @param {string} version1
 * @param {string} version2
 * @return {number}
 */

function compareVersion(version1, version2) {
  const v1Arr = version1.split(".");
  const v2Arr = version2.split(".");

  for (let i = 0; i < Math.max(v1Arr.length, v2Arr.length); i++) {
    const v1Num = Number(v1Arr[i] ?? 0);
    const v2Num = Number(v2Arr[i] ?? 0);

    if (v1Num > v2Num) {
      return 1;
    } else if (v1Num < v2Num) {
      return -1;
    }
  }

  return 0;
}

// Usage example
console.log(compareVersion("12.1.0", "12.0.9")); // => 1, meaning first one is greater
console.log(compareVersion("12.1.0", "12.1.2")); // => -1, meaning latter one is greater
console.log(compareVersion("5.0.1", "5.0.1")); // => 0, meaning they are equal.
Salin selepas log masuk

Pengisihan nombor versi

/**
 * @param {string[]} versions
 * @return {string[]}
 */

function sortVersions(versions) {
  return versions.sort((a, b) => {
    const aParts = a.split(".").map(Number);
    const bParts = b.split(".").map(Number);

    for (let i = 0; i < Math.max(aParts.length, bParts.length); i += 1) {
      const aPart = aParts[i] ?? 0;
      const bPart = bParts[i] ?? 0;

      if (aPart !== bPart) {
        return aPart - bPart;
      }
    }

    return 0;
  });
}

// Usage example
const sortedVersions = sortVersions([
  "0.1.1",
  "2.3.3",
  "0.302.1",
  "4.2",
  "4.3.5",
  "4.3.4.5",
]);
console.log(sortedVersions); // => [ '0.1.1', '0.302.1', '2.3.3', '4.2', '4.3.4.5', '4.3.5' ]
Salin selepas log masuk

Mampatkan rentetan

/**
 * @param {string} str
 * @return {string}
 */

function compress(str) {
  if (!str) {
    return "";
  }

  let compressed = "";
  let count = 1;

  for (let i = 1; i <= str.length; i += 1) {
    if (i < str.length && str[i] === str[i - 1]) {
      count += 1;
    } else {
      compressed += str[i - 1];
      if (count > 1) {
        compressed += count;
      }
      count = 1;
    }
  }

  return compressed;
}

// Usage example
console.log(compress("a")); // 'a'
console.log(compress("aa")); // 'a2'
console.log(compress("aaa")); // 'a3'
console.log(compress("aaab")); // 'a3b'
console.log(compress("aaabb")); // 'a3b2'
console.log(compress("aaabba")); // 'a3b2a'
Salin selepas log masuk

Nyahmampat rentetan

/**
 * @param {string} str
 * @returns {string}
 */

function uncompress(str) {
  const stack = [];
  let currentNum = 0;
  let currentStr = "";

  for (const char of str) {
    if (char >= "0" && char <= "9") {
      currentNum = currentNum * 10 + Number(char);
    } else if (char === "(") {
      stack.push([currentStr, currentNum]);
      currentStr = "";
      currentNum = 0;
    } else if (char === ")") {
      const [prevStr, num] = stack.pop();
      currentStr = prevStr + currentStr.repeat(num);
    } else {
      currentStr += char;
    }
  }

  return currentStr;
}

// Usage example
console.log(uncompress("3(ab)")); // => 'ababab'
console.log(uncompress("3(ab2(c))")); // => 'abccabccabcc'
Salin selepas log masuk

Cari panjang perkataan terpanjang dalam rentetan

/**
 * @param {string} str
 * @return {number}
 */

function longestLength(str) {
  const strArr = str.split(" ");
  let length = 0;

  for (let i = 0; i < strArr.length; i++) {
    if (strArr[i].length > length) {
      length = strArr[i].length;
    }
  }
  return length;
}

// Usage example
console.log(longestLength("The longest word is thelongestword")); // => 14
Salin selepas log masuk

Cari perkataan dengan panjang terpanjang dalam rentetan

/**
 * @param {string} str
 * @return {string[]}
 */

function longestWord(str) {
  const strArr = str.split(" ");
  const result = [];
  let max = 0;

  for (const char of strArr) {
    if (char.length > max) {
      max = char.length;
    }
  }

  for (const char of strArr) {
    if (char.length === max) {
      result.push(char);
    }
  }

  return result.join("");
}

// Usage example
console.log(longestWord("The longest word is thelongestword")); // => "thelongestword"
Salin selepas log masuk

Watak yang paling kerap muncul

/**
 * @param {string} str
 * @returns {string | string[]}
 */

function count(str) {
  const map = new Map();
  const result = [];

  for (const char of str) {
    map.set(char, (map.get(char) ?? 0) + 1);
  }

  const max = Math.max(...map.values());

  for (const [key, value] of map) {
    if (value === max) {
      result.push(key);
    }
  }

  return result.length === 1 ? result[0] : result;
}

// Usage example
console.log(count("abbccc")); // => 'c'
console.log(count("abbcccddd")); // => ['c', 'd'];
Salin selepas log masuk

Dapatkan panjang rentetan (emoji sokongan)

/**
 * @param {String} str
 * @return {Number}
 */

function getStringLength(str) {
  return Array.from(new Intl.Segmenter().segment(str)).length;
}

// Usage example
console.log(getStringLength("test?")); // => 5
console.log("test?".length); // => 6
Salin selepas log masuk

Rujukan

  • Alfanumerik - Wikipedia.org
  • Konvensyen penamaan (pengaturcaraan) - Wikipedia.org
  • 79. tukar snake_case kepada camelCase - BFE.dev
  • Versi perisian - Wikipedia.org
  • 157. semver compare - BFE.dev
  • 165. Bandingkan Nombor Versi - LeetCode
  • 97. mampatkan rentetan - BFE.dev
  • 173. nyahmampat rentetan - BFE.dev
  • 145. watak yang paling kerap muncul -BFE.dev

Atas ialah kandungan terperinci Rentetan - Cabaran JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!