如何在java中返回字符串中最长的字符序列?

时间:2014-02-13 08:39:55

标签: 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;
    }
}

6 个答案:

答案 0 :(得分:5)

你应该有一个计数器来计算现在最长序列的数量。当您找到更长的序列时,您应该重置result并相应地更新计数器。

但是,您可以获得更好的解决方案:

  • 有一个大小为26的数组(英文字母的大小)。现在你迭代String并为其中的每个char添加1,在helper数组的相应单元格中。
  • 使用HashMap作为char及其显示为的数字。如果它是新的char,您只需设为0值,如果存在,则递增现有的

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

答案 1 :(得分:4)

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. 

答案 2 :(得分:2)

如果有三个'l'你只添加两个'l'并且在下一步中是两个'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;
}

答案 3 :(得分: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;
}

答案 4 :(得分: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作为输出,这在给定的字符串中发生了最多次。

答案 5 :(得分: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;
        }
    }
}

这将通过所有测试用例。