2014-02-13 34 views
4

以下是我最終做的,但我沒有找到正確的答案。如何在java中返回字符串中最長的字符序列?

示例 - 如果序列爲「hellloo」,則輸出爲「lll」。請告訴我什麼是錯的?

public class LongestSequenceOfChar { 
    static String testcase1="hellloo"; 

    public static void main(String[] args) { 
     LongestSequenceOfChar test = new LongestSequenceOfChar(); 
     String result = test.longestSequenceOfChar(testcase1); 
     System.out.println(result); 
    } 
    public String longestSequenceOfChar(String str){ 
     String result=""; 
     for(int i=0;i<str.length();i++){ 
      char ch=str.charAt(i); 
      for(int j=i+1;j<str.length();j++){ 
       char ch1=str.charAt(j); 
       if(ch!=ch1){ 
        continue; 
       } 
       result+=ch; 
      } 
     } 
     return result; 
    } 
} 
+0

正如Sotirios所說,爲這類任務學習調試器是非常有用的。只需在方法開始處放置斷點,並逐步檢查結果發生了什麼。 –

+0

我是java.I的初學者,預計不會使用函數。我只能在loop的幫助下做到這一點。請幫助。 –

回答

2

如果有三個'l',你只需要添加兩個,下一步是兩個'l',然後添加其中一個。然後與兩個'o'一樣,你要添加一個。你只需要清除結果字符串,當你走到下一個字母,並保存結果之前,另一個變量,但只有當它是更長!

public String longestSequenceOfChar(String str){ 
    String interimresult=""; 
    String result="";    //final result 
    for(int i=0;i<str.length();i++){ 
     char ch=str.charAt(i); 
     interimresult += ch;  //add the letter once 
     for(int j=i+1;j<str.length();j++){ 
      char ch1=str.charAt(j); 
      if(ch!=ch1){ 
       break; 
      } 
      interimresult +=ch; 
     } 
     if(interimresult.length()>result.length())//store the result if it is longer 
      result = interimresult; 
     interimresult = "";     //clear to continue with the next letter 
    } 
    return result; 
} 
+0

非常感謝你的幫助。我發現我的錯誤@kai –

+0

你的代碼正在返回字符串中發生最多的字符,但我必須找到最長的字符序列。例如,如果字符串是「壓力」,那麼輸出將是「ss」,但它是給輸出「rr」。 –

+0

現在它可以工作,但這是一個很小的錯誤,你可以自己找到它。你只需要改變繼續打破。 – kai

5

您應該有一個計數器來計算現在最長的序列號。當找到更長的序列時,應該重置result並相應地更新計數器。

但是,你可以有更好的解決方案:

  • 有大小26(英文字母的大小)的數組。現在你迭代字符串,並且在其中每個char你在助手數組的相應單元格中加1。
  • 使用HashMap具有char作爲關鍵,它表現爲數量。如果它是一個新的char,你只需它與0值,如果它存在,你增加現有的

提示:使用調試器,它可以挽救你的生命。

+1

我正在建議更多的面向對象方法。有一個'Letter'類的值和頻率。這提供了一些直接映射,並可能使代碼更清晰。只是評論給OP另一個角度。 – christopher

3
1. Create a HashMap<Character,Integer>.. Integer-->count 
2. Start from the beginning of your String.. For each character, check if it is already present in the hashmap 
    a. If Yes, just increment the count 
    b. if No, then add the character as key to the Map and set its count value to 1. 
+0

由於我是一個初學者在java.I不知道Hashmap及其用法?任何更簡單的解決方案將有所幫助。 –

+0

@ user3305143 - 這可能比你的方法更容易...... :) .. 5到6行代碼就可以做到這一點.. – TheLostMind

2

這裏是一個解決方案:

public String longestSequenceOfChar(String str) { 
    String result = ""; 

    for (int i = 0; i < str.length(); i++) { 
     int j = i; 
     while(j < str.length() && str.charAt(j) == str.charAt(i)) { 
      j++; 
     } 

     // If this one is longer than previous, then asign it to result. 
     if(j - i > result.length()) { 
      result = str.substring(i, j); 
     } 
    } 
    return result; 
} 
+0

非常感謝你幫助我解決這個問題@ashot –

+0

歡迎你@ user3305143,這對我很有趣 –

+0

@ user3305143,BTW更有效的「補丁」:)刪除'i ++'從for循環和'if {}'(在if之外)之後添加'i = j'; –

0

嘗試......

public class HelloWorld { 

    public static void main(String[] args) { 
     System.out.println(maxLen(null)); 
     System.out.println(maxLen("")); 
     System.out.println(maxLen("a")); 
     System.out.println(maxLen("aa")); 
     System.out.println(maxLen("abcddd")); 
     System.out.println(maxLen("abcd")); 
     System.out.println(maxLen("aabbba")); 
    } 

    public static String maxLen(String input) { 
     // Avoid NPEs 
     if (input == null) { 
      return null; 
     } 
     int maxLen = 0; 
     int tempLen = 0; 
     char prevChar = 0; 
     char c = 0; 
     char repeatChar = 0; 
     for (int i = 0; i < input.length(); i++) { 
      c = input.charAt(i); 
      if (c == prevChar) { 
       tempLen++; 
       if (tempLen > maxLen) 
        repeatChar = c; 
      } else { 
       maxLen = (tempLen > maxLen) ? tempLen : maxLen; 
       prevChar = c; 
       tempLen = 1; 
      } 
     } 
     maxLen = (tempLen > maxLen) ? tempLen : maxLen; 
     if (maxLen == 0 || maxLen == 1) 
      return "no sequence found"; 
     else { 
      String str = ""; 
      for (int i = 1; i <= maxLen; i++) 
       str += String.valueOf(repeatChar); 
      return str; 
     } 
    } 
} 

這將通過所有的測試案例。

1

這可以使用HashMap輕鬆解決。結帳此示例代碼:

import java.util.Collections; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Map.Entry; 

public class MaximumOccuringCharUsingHashMap { 
    public static void main(String[] args) { 
    String test = "test samples"; 
    MaximumOccuringCharUsingHashMap mc = 
     new MaximumOccuringCharUsingHashMap(); 
    System.out.println(mc.findMaximunOccurenceCharacter(test)); 
} 
    char findMaximunOccurenceCharacter(String input){ 
     Map<Character, Integer> countHash = 
      new HashMap<Character, Integer>(); 
     for(int i=0; i<input.length() ;i++){ 
      char currentChar = input.charAt(i); 
      if(countHash.get(currentChar)==null){ 
       countHash.put(currentChar, 1); 
      }else{ 
       countHash. 
       put(currentChar, countHash.get(currentChar)+1); 
      } 
     } 

     int max = Collections.max(countHash.values()); 

     char maxCharacter =0; 
     for(Entry<Character, Integer> entry :countHash.entrySet()){ 
      if(entry.getValue() == max){ 
       maxCharacter = entry.getKey(); 
      } 
     } 
     return maxCharacter; 
    } 
} 

上面的代碼將打印s作爲輸出,這是發生在給定的字符串中的最大次數。

相關問題