Skip to the code
cf.
+10 XP

#624 Shorter of Raw or Encoded

easy

A sync service compresses small text fields before sending them, but only when it actually helps.

Encode text by writing each run of equal characters as the character followed by the run's length, so aaab becomes a3b1. Write maybeCompress(text) that returns the encoded string if it is strictly shorter than text, and text itself otherwise.

Example 1

Input: text = "aaaaabbb"
Output: "a5b3"

a5b3 has 4 characters, fewer than 8.

Example 2

Input: text = "abc"
Output: "abc"

a1b1c1 would be longer, so the text is kept.

Constraints

  • 0 <= text.length <= 10^5
  • text contains letters only.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).