using System.Text.RegularExpressions;
public class Solution {
public string FreqAlphabets(string s) {
var lookup = new Dictionary<string, char>();
var rx = new Regex(@"\d{2}#|\d{1}");
var alphabet = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#";
var c = 'a';
foreach (var match in rx.Matches(alphabet).Cast<Match>()) {
lookup[match.Value] = c++;
}
var sb = new StringBuilder();
foreach (var match in rx.Matches(s).Cast<Match>()) {
sb.Append(lookup[match.Value]);
}
return sb.ToString();
}
}
Optimized:
public class Solution {
public string FreqAlphabets(string s) {
var sb = new StringBuilder();
for (var i = 0; i < s.Length; ) {
if (i+2 < s.Length && s[i+2] == '#') {
sb.Append((char)('a' + (s[i]-'0')*10 + s[i+1]-'0' - 1));
i += 3;
} else {
sb.Append((char)('a' + s[i]-'0' - 1));
++i;
}
}
return sb.ToString();
}
}
Source:
https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/
No comments:
Post a Comment