我有這個代碼壓縮給定字串中的字符并用它們的count替換重復的相鄰字符。
考慮以下示例:
輸入:
aaabbccdsa
期望輸出:
a3b2c2dsa
我的代碼作業正常,但我認為重復條件是否可以洗掉。
public class Solution {
public static String getCompressedString(String str) {
String result = "";
char anch = str.charAt(0);
int count = 0;
for (int i = 0; i < str.length(); i ) {
char ch = str.charAt(i);
if (ch == anch) {
count ;
} else {
if (count == 1) { // from here
result = anch;
} else {
result = anch Integer.toString(count);
} // to here
anch = ch;
count = 1;
}
if (i == str.length() - 1) {
if (count == 1) { // from here
result = anch;
} else {
result = anch Integer.toString(count);
} // to here
}
}
return result;
}
}
在此解決方案中,以下代碼重復了兩次
if (count == 1) {
result = anch;
} else {
result = anch Integer.toString(count);
}
請注意,我不想使用單獨的方法來重復邏輯。
uj5u.com熱心網友回復:
您可以取消 if 陳述句。
public static String getCompressedString(String str) {
char[] a = str.toCharArray();
StringBuilder sb = new StringBuilder();
for(int i=0,j=0; i<a.length; i=j){
for(j=i 1;j < a.length && a[i] == a[j]; j );
sb.append(a[i]).append(j-i==1?"":j-i);
}
return sb.toString();
}
}
uj5u.com熱心網友回復:
您可以使用這種方法,如下所述:
代碼:
public class Test {
public static void main(String[] args) {
String s = "aaabbccdsaccbbaaadsa";
char[] strArray = s.toCharArray();
char ch0 = strArray[0];
int counter = 0;
StringBuilder sb = new StringBuilder();
for(int i=0;i<strArray.length;i ){
if(ch0 == strArray[i]){//check for consecutive characters and increment the counter
counter ;
} else { // when character changes while iterating
sb.append(ch0 "" (counter > 1 ? counter : ""));
counter = 1; // reset the counter to 1
ch0 = strArray[i]; // reset the ch0 with the current character
}
if(i == strArray.length-1){// case for last element of the string
sb.append(ch0 "" (counter > 1 ? counter : ""));
}
}
System.out.println(sb);
}
}
樣本輸入/輸出:
Input:: aaabbccdsaccbbaaadsa
Output:: a3b2c2dsac2b2a3dsa
Input:: abcdaaaaa
Output:: abcda5
uj5u.com熱心網友回復:
由于else第二個和第二個的主體if是相同的,所以我們可以通過更新條件來合并它們。更新后的函式主體將是:
String result = "";
char anch = str.charAt(0);
int count = 0;
char ch = str.charAt(0); // declare ch outside the loop, and initialize to avoid error
for (int i = 0; i < str.length(); i ) {
ch = str.charAt(i);
if (ch == anch) {
count ;
}
// check if the second condition is false, or if we are at the end of the string
if (ch != anch || i == str.length() - 1) {
if (count == 1) { // from here
result = anch;
} else {
result = anch Integer.toString(count);
} // to here
anch = ch;
count = 1;
}
}
// add the condition
// if count is greater than or
// if the last character added already to the result
if (count > 1 || (len < 2 || result.charAt(len - 2) != ch)) {
result = ch;
}
return result;
測驗用例:
我已經在以下輸入上測驗了解決方案:
aaabbccdsa -> a3b2c2dsa
aaab -> a3b
aaa -> a3
ab -> ab
aabbc -> a2b2c
可選的
如果你想讓它更短,你可以更新這兩個條件。
if (count == 1) { // from here
result = anch;
} else {
result = anch Integer.toString(count);
} // to here
作為
result = anch;
if (count != 1) { // from here
result = count;// no need to convert (implicit conversion)
} // to here
uj5u.com熱心網友回復:
這是使用 Stream API 和正則運算式的單陳述句解決方案:
public static final Pattern GROUP_OF_ONE_OR_MORE = Pattern.compile("(.)\\1*");
public static String getCompressedString(String str) {
return GROUP_OF_ONE_OR_MORE.matcher(str).results()
.map(MatchResult::group)
.map(s -> s.charAt(0) (s.length() == 1 ? "" : String.valueOf(s.length())))
.collect(Collectors.joining());
}
main()
public static void main(String[] args) {
System.out.println(getCompressedString("aaabbccdsa"));
System.out.println(getCompressedString("awswwwhhhp"));
}
輸出:
a3b2c2dsa // "aaabbccdsa"
awsw3h3p // "awswwwhhhp"
它是如何作業的
正則運算式"(.)\\1*"正在捕獲一組長(.)度1或更大的相同字符。其中.- 表示任何符號,并且\\1是對該組的反向參考。
方法“為匹配模式的輸入序列的每個子序列回傳匹配結果流”。Matcher.results()
剩下的唯一事情是評估每個組的長度并在收集到結果字串之前進行相應的轉換。
鏈接:
- 關于正則運算式的快速教程。
- 關于lambda 運算式和流的官方教程
uj5u.com熱心網友回復:
你可以這樣做:
public static String getCompressedString(String str) {
String result = "";
int count = 1;
for (int i = 0; i < str.length(); i ) {
if (i 1 < str.length() && str.charAt(i) == str.charAt(i 1)) {
count ;
} else {
if (count == 1) {
result = str.charAt(i);
} else {
result = str.charAt(i) "" count;
count = 1;
}
}
}
return result;
}
我擺脫了重復的代碼,它按預期進行。
uj5u.com熱心網友回復:
您可以使用具有以下 3 個引數的函式:result、anch、count。
這種東西:
private static String extractedFunction(String result,int count, char anch) {
return count ==1 ? (result anch) : (result anch Integer.toString(count) );
}
從這兩點進行函式呼叫,如下所示:
result = extractedFunction(result,count,anch);
uj5u.com熱心網友回復:
嘗試這個。
static final Pattern PAT = Pattern.compile("(.)\\1*");
static String getCompressedString(String str) {
return PAT.matcher(str)
.replaceAll(m -> m.group(1)
(m.group().length() == 1 ? "" : m.group().length()));
}
測驗用例:
@Test
public void testGetCompressedString() {
assertEquals("", getCompressedString(""));
assertEquals("a", getCompressedString("a"));
assertEquals("abc", getCompressedString("abc"));
assertEquals("abc3", getCompressedString("abccc"));
assertEquals("a3b2c2dsa", getCompressedString("aaabbccdsa"));
}
此處使用的正則運算式"(.)\\1*"匹配任何相同字符的序列。.replaceAll()將 lambda 運算式作為引數,每次模式匹配時計算 lambda 運算式,并用結果替換原始字串。向 lambda 運算式傳遞一個Matcher包含匹配結果的物件。在這里,我們在變數中接收這個物件m。m.group()回傳整個匹配的子字串,m.group(1)回傳它的第一個字符。
如果輸入字串為"aaabbccdsa",則按如下處理。
m.group(1) m.group() returned by lambda
a aaa a3
b bb b2
c cc c2
d d d
s s s
a a a
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516497.html
標籤:爪哇细绳重复
