classSolution{public:stringencode(strings){constintn=s.length();// dp[i][j] := shortest encoded string of s[i..j]dp.resize(n,vector<string>(n));returnencode(s,0,n-1);}private:vector<vector<string>>dp;stringencode(conststring&s,inti,intj){if(!dp[i][j].empty())returndp[i][j];conststring&curr=s.substr(i,j-i+1);dp[i][j]=curr;if(dp[i][j].length()<5)returndp[i][j];// Try all possible partitionsfor(intk=i;k<j;++k){conststring&l=encode(s,i,k);conststring&r=encode(s,k+1,j);if(l.length()+r.length()<dp[i][j].length())dp[i][j]=l+r;}// Try to compress the string// E.g. s = aabaabaab -> 3[aab]for(intk=i;k<=j;++k){conststring&pattern=s.substr(i,k-i+1);if(curr.length()%pattern.length()==0&®ex_replace(curr,regex(pattern),"").empty()){conststring&candidate=to_string(curr.length()/pattern.length())+'['+encode(s,i,k)+']';if(candidate.length()<dp[i][j].length())dp[i][j]=candidate;}}returndp[i][j];}};
classSolution{publicStringencode(Strings){finalintn=s.length();// dp[i][j] := shortest encoded String of s[i..j]dp=newString[n][n];returnencode(s,0,n-1);}privateString[][]dp;privateStringencode(finalStrings,inti,intj){if(dp[i][j]!=null)returndp[i][j];finalStringcurr=s.substring(i,j+1);dp[i][j]=curr;if(dp[i][j].length()<5)returndp[i][j];// Try all possible partitionsfor(intk=i;k<j;++k){finalStringl=encode(s,i,k);finalStringr=encode(s,k+1,j);if(l.length()+r.length()<dp[i][j].length())dp[i][j]=l+r;}// Try to compress theString// E.g. s = aabaabaab -> 3[aab]for(intk=i;k<=j;++k){finalStringpattern=s.substring(i,k+1);if(curr.length()%pattern.length()==0&&curr.replaceAll(pattern,"").isEmpty()){finalStringcandidate=String.valueOf(curr.length()/pattern.length())+"["+encode(s,i,k)+"]";if(candidate.length()<dp[i][j].length())dp[i][j]=candidate;}}returndp[i][j];}}
classSolution{public:stringencode(strings){constintn=s.length();// dp[i][j] := shortest encoded string of s[i..j]vector<vector<string>>dp(n,vector<string>(n));for(intd=0;d<n;++d){for(inti=0;i+d<n;++i){constintj=i+d;conststring&curr=s.substr(i,j-i+1);dp[i][j]=curr;if(dp[i][j].length()<5)continue;// Try all possible partitionsfor(intk=i;k<j;++k)if(dp[i][k].length()+dp[k+1][j].length()<dp[i][j].length())dp[i][j]=dp[i][k]+dp[k+1][j];// Try to compress theString// E.g. s = aabaabaab -> 3[aab]for(intk=i;k<=j;++k){conststring&pattern=s.substr(i,k-i+1);if(curr.length()%pattern.length()==0&®ex_replace(curr,regex(pattern),"").empty()){conststring&candidate=to_string(curr.length()/pattern.length())+'['+dp[i][k]+']';if(candidate.length()<dp[i][j].length())dp[i][j]=candidate;}}}}returndp[0][n-1];}};