簡體   English   中英

Java 中的字符串操作問題

[英]String Manipulation Problems in Java

我昨天在面試中問了以下兩個問題

1> 給定一個字符串,計算一個新字符串,其中原始字符串中相鄰的相同字符用“*”分隔。

示例如下所示:
函數名是public String pairStar(String str)

 pairStar("hello") → "hel*lo"     
 pairStar("xxyy") → "x*xy*y"          
 pairStar("aaaa") → "a*a*a*a"

2> 給定一個字符串,計算一個新字符串,其中所有小寫的 'x' 字符都已移動到字符串的末尾。

示例如下所示:
函數名是public String endX(String str)

endX("xxre") → "rexx"     
endX("xxhixx") → "hixxxx"     
endX("xhixhix") → "hihixxx"

我不確定如何完成給定的一組問題,並且正在努力解決這個問題

在第一種情況下,您可以遍歷字符串以跟蹤前一個字符並將其與當前字符進行比較。 使用 StringBuilder 構建新字符串。

在第二個中,使用兩個字符串構建器(一個用於 x 以外的字符,一個用於 x)迭代,最后將它們組合起來。

這在 30 秒內就在我的腦海中,並且是最簡單的方法。 第二個想法是我可能會使用正則表達式,現在我又想了 10 秒 :)

對於 1),這是一個非常簡單的正則表達式方式:

  String in = "helllo goodbye";
  String out = in.replaceAll("(.)(?=\\1)", "$1*");
  System.out.println(out);

印刷:

hel*l*lo go*odbye

解釋:

(.)     //match any one character into group 1
(?=\\1) //positive lookahead for that same character by backreferencing group 1

$1*     //replace that one character with the character followed by *

稍后我可能會嘗試解決 2),但我不喜歡將多個問題合並為一個。

編輯

好吧,因為我有正則表達式的心情,這里是 2):

  String in = "xhixhix";
  String out = in;
  while (!out.matches("[^x]*x*")) {
     out = out.replaceAll("x(.*)", "$1x");
  }
  System.out.println(out);

這將x(something)替換為(something)x直到所有x都位於字符串的末尾。 不過,我確信使用/比使用正則表達式有更好的方法。

也許我誤解了這個問題,但如果不是,如果看起來很簡單。 您的方法可能類似於數字 1:

public String pairStar(String s) {
    StringBuilder answer = new StringBuilder();
    char lastChar = s.charAt(0);
    answer.append(lastChar);

    for (int i = 1; i < s.length(); i++) {
        char currentChar = s.charAt(i);

        if (currentChar == lastChar) {
             answer.append("*");
        }
        answer.append(currentChar);
        lastChar = currentChar;
    }
    return answer.toString();
}

對於第二個:

循環遍歷字符串,將所有非小寫 x 復制到一個新字符串中,同時保持 x 的計數。 最后,只需添加相關數量的 x 即可生成最終字符串。

public String endX(String str)
{
    StringBuilder s = new StringBuilder();
    int x = 0;

    for (int i = 0; i < str.length(); ++i)
    {
        if (str.charAt(i) == 'x')
        {
            ++x;
        }
        else
        {
            s.append(str.charAt(i));
        }
    }

    for (int i = 0; i < x; ++i)
    {
        s.append('x');
    }

    return s.toString();
}

對於 1,您需要一個具有兩種狀態的狀態機:(a) 與之前不同和 (b) 與之前相同。 起始狀態是(a)。 對於每個字母,您必須檢查您處於哪個狀態,輸出一個字符並相應地更改狀態。 對於在狀態 (b) 中讀取的每個字母,您還輸出一個“*”。

對於 2,您需要一個數組,您可以在其中向左移動元素,並在最后推送。 1. 在末尾推送一個監視器標記(對於停止條件很有用) 2. 遍歷所有字母:當找到“x”時,將所有元素向左移動,在末尾推送 x 並計算您看到的 x 的數量。 3. 看到監控令牌就停下來

我通常用偽代碼開始這樣的問題,然后轉向實際的實現。

對於問題 1,這是我腦海中偽代碼的工作原理

for each character in the input string{
 if the previous character is the same{
  append a star to output string
 }
 append the character to the output string
}

對於問題 2

for each character in the input string{
  if character is an x{
   increment x counter
  } else {
   append the character to the output string
  }
}
x counter times{
  append x to the output string
}

對於第一個問題:

public class StreamGobbler {

    public static void main(String[] a) {

        String s = "xxyy";

        StringBuffer sb = new StringBuffer(s);

        for(int i=0; i < sb.length()-1; i++) {
            if(sb.charAt(i) == sb.charAt(i+1)) {
                sb.insert(i+1, "*");
                i++;
            }
        }

        System.out.println(sb.toString());
    }
}

打印: x*xy*y

對於你的第一個問題

public String pairStar(String str){
        StringBuilder sb = new StringBuilder(str);
        for (int i = 0; i < sb.length()-1; i++) {
            if(sb.charAt(i)==sb.charAt(i+1)){
                sb.insert(++i, '*');
            }
        }
        return sb.toString();
    }

對於你的第二個問題

public String endX(String str){
        StringBuilder sb = new StringBuilder(str);
        int length = sb.length()-1;
        for (int i = 0; i < length; i++) {
            if(sb.charAt(i)=='x'){
                sb.deleteCharAt(i--);
                sb.append('x');
                length--;
            }
        }
        return sb.toString();
    }
public class IdenticalChars {

    /**
     * separates any two same n adjacent characters of any string
     * by a * 
     */
    public static void main(String[] args) {
        StringBuilder sb=new StringBuilder();
        String s="aaabcgghelllloii";
        for(int i=0;i+1<s.length();i++){
            if((s.charAt(i)!=s.charAt(i+1)&&(i==0))){
                sb.append(s.charAt(i)+" "+s.charAt(i+1));
                //System.out.println(sb.toString());
            }
            else if((s.charAt(i)!=s.charAt(i+1)&&(i>0))){
                sb.append(s.charAt(i+1));
            }
            else if((s.charAt(i)==s.charAt(i+1))&&(i>0)){
                sb.append("*"+s.charAt(i+1));

            }
            else if((s.charAt(i)==s.charAt(i+1))&&(i==0)){
                sb.append(s.charAt(i)+"*"+s.charAt(i+1));
                }
        }

        System.out.println(sb.toString());
    }

}

輸出::a*a*abcg*ghel*l*l*loi*i

步驟 1. 告訴他們推它然后改用 python!

第2步。:

>>> strin = 'thixs ixs xan XArbitrarxy Stxrxing'
>>> xcnt = strin.count('x')
>>> result = ''.join(i for i in strin if i != 'x')
>>> result = result + ('x' * xcnt)
>>> print result
this is an XArbitrary Stringxxxxxx

這些可以通過遞歸完成。

當 str 長度達到 0 時,第一個中斷。否則,它檢查當前字符和下一個字符是否相同,如果相同,則返回帶有“*”字符串的當前字符。 否則它只是獲取當前字符串並循環返回。 1)

public String pairStar(String str) {
  int i = 0;
  if (str.length() == 0)
    return str;
  else if (str.length()-1 > i && str.charAt(i) == str.charAt(i+1))
    return str.charAt(i) + "*" + pairStar(str.substring(i+1));
  return str.charAt(i) + pairStar(str.substring(i+1));
} 

當 str 長度為 0 時,這也會中斷。否則,如果 str 字符是“x”,則在內存中保留“x”字符的同時循環。 否則獲取當前字符,最后將 'x' 放在內存中。

public String endX(String str) {
  int i = 0;
  if (str.length() == 0)
    return str;
  else if (str.charAt(i) == 'x')
    return endX(str.substring(i+1)) + 'x' ;
  return str.charAt(i) + endX(str.substring(i+1));
}

這是使用遞歸的一個簡單答案:)

public String pairStar(String str) {
     if(str.isEmpty())return ""; // our exit condition for recursion
     String sub1 = str.substring(0,1); // take the first char
     String sub2 = ""; 
     if(str.length()>1)sub2 = str.substring(1,2); // take second char if it it contains at least 2 chars
     if(sub1.equals(sub2)) return sub1+"*"+pairStar(str.substring(1)); //if two chars are equal putting star between
     return sub1 + pairStar(str.substring(1));//else continue as usual 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM