Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

javascript - String Compression with a particular case

Examples are

let string1 = "AAAAA"
Output: 4A1A
My output: 4A

let string2 = "AAAAAAAAABBBBBCCCCDD"
output : 4A4A1A4B1B4C2D
My output: 4A4A4B2B4C2D

If the length of a particular character is greater than 4, start counting from 1 again.

I am unable to print the one remaining character every time. Please refer to the above example:

And here is my code. Please try to improve my code and not give a new solution as much as possible.

function stringCompress(str) {
  let sum = 0;
  let res = "" 
  let demo = []
  for(let i = 0; i < str.length;i++){
      demo.push(i+"=" +str.substring(i,i+1))
      if(str.substring(i,i+1) != str.substring(i+1,i+2) || sum == 4 ){
          sum = sum+1
          let temp = 0;
          if(sum > 4){
              sum = 4
              temp = 1
          }
          res += sum+str.substring(i,i+1);   
          
          if(temp == 1){
              sum = temp
          }else{
            sum = 0;  
          }
          
          
      }
      else{
          sum = sum +1
      }
      
  }
   
  return res
}

let d = "AAAAAAAAABBBBBCCCCDD"

console.log(stringCompress(d))
question from:https://stackoverflow.com/questions/66048091/string-compression-with-a-particular-case

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's simplify a bit. Splitting the string into an array of chunks of max 4 equal characters, subsequently use Array.map to add the lengths of every chunk and join the result.

console.log(compress("AAAAA"));
console.log(compress("AAAAAAAAABBBBBCCCCDD"));

function compress(str) {
  let strings = [];
  let chunk = '';
  for (let i = 0; i < str.length; i += 1) {
    // if [chunk] contains a character and its length is not 4 and 
    // its first character equals the current character add 
    // the current character to [chunk]
    if (chunk.length > 0 && chunk.length < 4 && str[i] === chunk[0]) {
      chunk += str[i];
    } else {
      // if [chunk] is not "", push it to [strings]
      chunk.length && strings.push(chunk);
      // reassign [chunk] using the current value
      chunk = str[i];
    }
  }
  // chunk may not be empty yet
  if (chunk.length) {
    strings.push(chunk);
  }
  // convert to string
  return strings.map(v => `${v.length}${v[0]}`).join("")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...