-2个字节,感谢@Cyoce
@Cyoce的想法多了-17个字节
-6个字节,感谢@KevinCruijssen
s->{String c="[RSGTBP]",v="[OIEA]",o="([256789])",e="([0134])";boolean b=s.matches("(c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+".replace("c",c).replace("v",v));int i=-1;for(s=b?s.replaceAll("[UN]",""):s.matches("[0-9]+")?s.replaceAll(e+"(?="+e+")","$1N").replaceAll(o+"(?="+o+")","$1U"):i/0+"";i<9;s=b?s.replace(v,c):s.replace(c,v)){c=++i+"";v="OIREASGTBP".charAt(i)+"";}return s;}
在线尝试!
replacement,java替换太冗长了。
该函数接受一个字符串,并返回从数字->字母翻译过来的字符串,反之亦然。输入无效时崩溃(您可以在tio示例中看到此错误,该示例在前10个测试用例中输出正确的值,然后在调试视图中显示除以零的错误而崩溃)
取消高尔夫(for循环的第一项和最后一项被抽出以提高可读性)
s-> {
String c="[RSGTBP]", v="[OIEA]", o="([256789])", e="([0134])";
boolean b=s.matches("(c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+".replace("c",c).replace("v",v)); // lovely regex, explained below
int i=-1;
s= b?
s.replaceAll("[UN]",""); // remove N's and U's
:s.matches("[0-9]+")?
s.replaceAll(e+"(?="+e+")","$1N").replaceAll(o+"(?="+o+")","$1U"); // add N's and U's for separating vowels and consonants
:i/0+""; // throw an error, looks like a sting for the ternary
for(;i<9;) {
c=++i+"";
v="OIREASGTBP".charAt(i)+"";
s=b?s.replace(v,c):s.replace(c,v); // if it started with numbers, go to letters, or vice versa
}
return s;
}
用于匹配数字的正则表达式很简单,但这是用于将字母与数字匹配的正则表达式
(c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+
( )+ every part of the word is
c$ a consonant at the end of the word
|v$ or a vowel at the end of the word
|(c|vN)(?=v) or a consonant or a vowel + N followed by a vowel
|(cU|v)(?=c) or a consonant + U or a vowel followed by a consonant
with c = [RSGTBP] and v = [OIEA]
GIGATESTER应该GIGATESUTER吗?