【问题标题】:How to return longest sequence of chars in a string in java?如何在java中返回字符串中最长的字符序列?
【发布时间】:2014-02-13 08:39:54
【问题描述】:

以下是我最终要做的,但我没有找到正确的答案。

示例 - 如果我有序列“hellloo”,则输出将是“llll”。请告诉我有什么问题?

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;
    }
}

【问题讨论】:

  • 正如 Sotirios 所提到的,为这类任务学习调试器非常有帮助。只需在方法的开头放置断点,然后逐步检查结果发生了什么。
  • 我是java的初学者。我不应该使用函数。我只能在循环的帮助下这样做。请帮助。

标签: java


【解决方案1】:

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

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

  • 有一个大小为 26 的数组(英文字母的大小)。现在您对 String 进行迭代,并为其中的每个 char 添加 1 在辅助数组的相应单元格中。
  • 使用HashMap,其中char 作为,其数字作为。如果它是一个新的char,您只需放入 0 值,如果它存在,则增加现有的

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

【讨论】:

  • 我打算建议一种更面向对象的方法。有一个带有值和频率的Letter 类。这提供了一些直接映射,并可能使代码更清晰。只评论给 OP 另一个角度。
【解决方案2】:
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. 

【讨论】:

  • 因为我是 java 初学者。我不知道 Hashmap 及其用途?任何更简单的解决方案都会有所帮助。
  • @user3305143 - 这可能比你的方法更容易...... :).. 5 到 6 行代码就可以了......
【解决方案3】:

如果有三个“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;
}

【讨论】:

  • 非常感谢您的帮助。我发现了我的错误@kai
  • 您的代码正在返回字符串中出现次数最多的字符,但我必须找到最长的字符序列。例如,如果字符串是“压力”,那么输出将是“ss”,但它是给出输出“rr”。
  • 现在它可以工作了,但这是一个很小的错误,你可以自己发现它。你只需要改变继续打破。
  • 但您的代码具有相同的行为。它也计算出现次数,因为你没有打破循环,就像 if(ch==ch1)result+ch;这就是计算发生次数的典型方法。
【解决方案4】:

这是一个解决方案:

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;
}

【讨论】:

  • 非常感谢您帮助我解决这个问题@ashot
  • @user3305143,顺便说一句更有效的“补丁”:) 从 for 循环中删除 i++ 并在 if{} 之后(在 if 之外)添加 i = j;
【解决方案5】:

这可以使用 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 作为输出,这在给定的字符串中出现了最大次数。

【讨论】:

    【解决方案6】:

    试试这个...

    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;
            }
        }
    }
    

    这将通过所有测试用例。

    【讨论】:

      猜你喜欢
      • 2021-04-14
      • 1970-01-01
      • 2020-03-04
      • 2023-02-25
      • 2022-08-10
      • 1970-01-01
      • 2020-03-28
      • 2016-02-14
      • 2017-05-12
      相关资源
      最近更新 更多