【问题标题】:find all palindromes in string查找字符串中的所有回文
【发布时间】:2014-03-31 06:40:50
【问题描述】:

我需要找到一个字符串中的所有回文。它需要用户输入

示例:“abbaalla”

它循环创建一个随着循环进行而改变的子字符串。

示例:检查回文“a”(真)“ab”(假)“abb”(假)“abba”(真)等等..

一旦达到单词的最大长度,它就会迭代子字符串的开头并重复

示例:检查回文“b”“bb”“bba”等..

我需要更改代码,以便一旦找到第一个最大的回文(“abba”),循环的开始将发生在该子字符串之后。所以下一个回文应该是“alla”

最终输出应该是一个包含所有回文的字符串。在这种情况下;

输出:“阿巴阿拉”

此程序当前也导致:字符串索引超出范围:-1

 public static String findAllPalindromes(String input){
     int indexStart = 0;
     int wordMax = input.length();
     int wordLength;
     String checkPalindrome;
     String allPalindromes = "";
     for (wordLength = 2; wordLength <= wordMax; wordLength++) {

         //creates a substring to check against isAllPalindrome method
         checkPalindrome = input.substring(indexStart, wordLength);
         //checks checkPalindrome string to see if it is a palindrome
         if (isAllPalindrome(checkPalindrome) == true){
             allPalindromes += " " + checkPalindrome;
             if (checkPalindrome.length() >= allPalindromes.length()){
                 allPalindromes = checkPalindrome;
             }
         }
         //once program reads string through once, increment index and scan text again
         if (wordLength == wordMax && indexStart < wordMax){
             indexStart++;
             wordLength = 0;
         }

     }
     System.out.println("The palindromes in the text are: ");
     System.out.println(allPalindromes);
     return allPalindromes;
 }

【问题讨论】:

  • 我们在为你做功课吗?
  • 这是一个家庭作业,我已经做了很多尝试来解决这个问题。寻求友好社区的帮助

标签: java loops palindrome


【解决方案1】:
public static Set<CharSequence> printAllPalindromes(String input) {
    if (input.length() <= 2) {
        return Collections.emptySet();
    }
    Set<CharSequence> out = new HashSet<CharSequence>();
    int length = input.length();
    for (int i = 1; i <= length; i++) {
        for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
            if (input.charAt(j) == input.charAt(k)) {
                out.add(input.subSequence(j, k + 1));
            } else {
                break;
            }
        }
    }
    return out;
}

【讨论】:

  • @kealtuve:在您的(问题)代码中:substring 方法采用第二个参数 index 而不是 length,因此您有两个错误:1)条件应为wordLength &lt; wordMax 2)input.substring(indexStart, indexStart+wordLength)
  • @jw23:它是否涵盖了 String = "aab" 其中回文为 "aa, a, b" 的情况?
  • 这种方式只涵盖奇数回文,没有单个字符。
  • 对于输入字符串 string -'adda' 给出的是空集,有什么想法吗?
  • 这个程序不认为aba 是回文。
【解决方案2】:

简单的蛮力方式-->

public class AllPalindromes {

    public static boolean checkPalindrome(String str) {
        for(int i=0;i<=str.length()/2;i++)
            if(str.charAt(i)!=str.charAt(str.length()-1-i))
                return false;
        return true;
    }

    public static void printAllPalindrome(String str) {
        for(int i=0;i<=str.length();i++)
            for(int j=i;j<str.length();j++)
                if(checkPalindrome(str.substring(i,j+1)))
                    System.out.println(str.substring(i,j+1));
    }

    public static void main(String[] args) {
        printAllPalindrome("abbaalla");
    }

}

【讨论】:

    【解决方案3】:

    这是显示所有回文的解决方案。 (只有那些长度大于 3 的回文。如果要全部打印,可以更改循环内的 if 条件。)

    请注意,@jw23 的解决方案不显示偶数长度的回文 - 仅显示奇数长度的回文。

        public class HelloWorld{
    
        public static void printPalindromes(String s) {
            if (s == null || s.length() < 3)
                return;
    
            System.out.println("Odd Length Palindromes:");
            // Odd Length Palindromes
            for (int i=1; i<s.length()-1; i++) {
                for (int j=i-1,k=i+1; j>=0 && k<s.length(); j--,k++) {
                    if (s.charAt(j) == s.charAt(k)) {
                        if (k-j+1 >= 3)
                            System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
                    }
                    else
                        break;
                }
            }
    
            System.out.println("\nEven Length Palindromes:");
            // Even Length Palindromes
            for (int i=1; i<s.length()-1; i++) {
                for (int j=i,k=i+1; j>=0 && k<s.length(); j--,k++) {
                    if (s.charAt(j) == s.charAt(k)) {
                        if (k-j+1 >= 3)
                            System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
                    }
                    else
                        break;
                }
            }
        }
    
        public static void main(String[] args){
            String s = "abcbaaabbaa";
            printPalindromes(s);
        }
    }
    

    【讨论】:

      【解决方案4】:
      public class Palindrome
      {
        static int count=0;
        public static void main(String args[])
        {
          Scanner sc=new Scanner(System.in);
          String s1=sc.next();
          String array[]=s1.split("");
          System.out.println("Palindromes are :");
          for(int i=0;i<=array.length;i++)
          {
              for(int j=0;j<i;j++)
              {
                  String B=s1.substring(j,i);
                  verify(B);
              }
          }
          System.out.println("\n"+count);
          sc.close();
        }
        public static void verify(String s1)
        {
          StringBuilder sb=new StringBuilder(s1);
          String s2=sb.reverse().toString();
          if(s1.equals(s2))
          {
              System.out.print(s1+" ");
              count++;
          }
        }
      }
      

      【讨论】:

        【解决方案5】:

        我自己的所有子串回文程序的逻辑

        public class Test1 {
        
            public static void main(String[] args) {
        
                String s = "bob";
        
                ArrayList<Character> chr = new ArrayList<Character>();
                ArrayList<String> subs= new ArrayList<String>();
        
                for (int i=0;i<s.length();i++)
                {
                    chr.add(s.charAt(i));
                }
        
                System.out.println(chr.toString());
                StringBuilder subString = new StringBuilder();
                for(int i=0; i < s.length();i++)
                {
                    for(int j=i+1;j<s.length();j++)
                    {
                        for(int k=i;k<=j;k++)
                        {
                            subString.append(chr.get(k));
        
                        }
                        System.out.println(subString.toString());
                        subs.add(subString.toString());
                        subString.setLength(0); 
                    }
                }
        
                System.out.println(subs);
        
                for(String st : subs)
                {
                    String st2 = new StringBuffer(st).reverse().toString(); 
                if(st.equals(st2))
                {
                    System.out.println(st+" is a palindrome");
                }
                else
                {
                    System.out.println(st+"  not a palindrome");
                }   
        
                }
            }
        
        }
        

        【讨论】:

          【解决方案6】:

          打印字符串中的所有回文

          import java.util.*;
          class AllPalindroms
          {
            public static void main(String args[])
            {
              String input = "abbaalla";      
              if (input.length() <= 1) 
              {
                  System.out.println("Not Palindrome Found.");
              }
              else
              {   
                  int length = input.length();            
                  Set<String> set = new HashSet<String>();
                  for (int i = 0; i <length; i++)
                  {
                      //if(i==0)
                      for (int j=i+1;j<length+1;j++) 
                      {
                          String s = input.substring(i, j);                   
                          StringBuffer sb = new StringBuffer(s);
                          sb.reverse();
          
                          if(s.equals(sb.toString()) && s.length()>1)
                          {                       
                              set.add(s);
                          }
                      }
                  }           
                  System.out.println(set);
              }
            }
          }
          

          【讨论】:

            【解决方案7】:

            我计算字符串中所有回文数的代码:

            导入 java.util.Scanner;

            公共类 CountPalindromeSapient { 静态整数 = 0;

            public static void main(String[] args) {
            
                Scanner sc = new Scanner(System.in);
                System.out.println("Enter the given string: ");
                String inputStr = sc.nextLine();
            
                countPalindrome(inputStr);
                System.out.println("\nTotal count of Palindromes are: "+count);     
                sc.close();
            }
            
            private static int countPalindrome(String inputStr) {
            
                int count = 0;
                int len = inputStr.length();
                int startIndex =0;
            
                String subString = "";
            
                System.out.println( "Possible substrings are: ");
                for (int i = 0; i < len; i++) {
                    for (int j = startIndex; j <= len; j++) {
                        subString = inputStr.substring(startIndex, j);
                        System.out.println(subString);
            
                        count = checkPalindrome(subString);
            
                    }
                    startIndex++;
                }
            
                return count;
            }
            
            private static int checkPalindrome(String subString) {
                // TODO Auto-generated method stub
                int subLen = subString.length();
                boolean isPalindrome = false;
                for(int k=0; k<subLen; k++,subLen-- ) {     // Important
                    if (subString.charAt(k) != subString.charAt(subLen -1)) {
                        isPalindrome =  false;
                        break;
                    }else {
                        isPalindrome = true;
                    }
                }
                if(isPalindrome == true) {
                    count ++;
                }
                return count;
            }
            

            }

            【讨论】:

              【解决方案8】:
                   class StringTest {
                  public static void main(String[] args) {
                      StringTest test = new StringTest();
                       boolean bool = test.checkPalindrom("abbaalla");
                      if(!bool)
                          System.out.println("String is not palindrom");
              
                  }
                  private boolean checkPalindrom(String k){
                      int[] count= new int[k.length()];
                      boolean[] arr = new boolean[k.length()];
                      for(int t=0;t<k.length();t++){
                          int j=0;
                          char ch = k.charAt(t);
                          for(int x=t+1;x<k.length();x++){
                          if(j<count.length){
                              if(ch == k.charAt(x))
                                  count[j] = x + 1;
                              else
                                  count[j] = 0;
                              j++;
                          }
              
                          }
                          arr[t] = workOnArr(count,t,k);
                      }
                      for(int z=0;z<arr.length;z++){
                          if(arr[z])
                              return true;
                      }
              
                      return false;
                  }
              private boolean workOnArr(int[] s,int z,String w){
                  int j = s.length - 1; 
                  while(j -- > 0){
                      if(s[j] != 0){
                          if(isPalindrom(w.substring(z, s[j]))){
                              if(w.substring(z, s[j]).length() > 1){
                                  System.out.println(w.substring(z, s[j]).length());
                                  System.out.println(w.substring(z, s[j]));
                              }
                              return true;
                          }
                      }
                  }
                  return false;
              }   
              
              private boolean isPalindrom(String s){
              
                  int j= s.length() -1;
                  for(int i=0;i<s.length()/2;i++){
                      if(s.charAt(i) != s.charAt(j))
                          return false;
                          j--;
                  }
              
                  return true;
              }
                  }
              



              输出:-
              给定的回文是:-
              abba, bb, aa, alla, ll

              【讨论】:

                【解决方案9】:

                问题:一个单词的所有回文。

                public class Test4 {
                    public static void main(String[] args) {
                         String a = "ProtijayiMeyeMADAMGiniiniGSoudiptaGina";
                        allpalindromicsubstrings(a);
                
                    }// main
                
                    private static void allpalindromicsubstrings(String a) {
                        Set<String> set = new HashSet<String>();
                        for (int i = 0; i < a.length(); i++) {
                            // odd length palindrome
                            expand(a, i, i, set);
                            // even length palindrome
                            expand(a, i, i + 1, set);
                
                        } // for
                        set.parallelStream().filter(words -> words.length() > 1).distinct().forEach(System.out::println);
                    }// ee
                
                    private static void expand(String a, int start, int last, Set<String> set) {
                        // run till a[start...last] is a palindrome
                        while (start >= 0 && last <= a.length() - 1 && a.charAt(start) == a.charAt(last)) {
                
                            set.add(a.substring(start, last + 1));
                            // expand in both directions
                            start--;
                            last++;
                
                        }
                    }// ee
                
                }
                

                单词中的输出回文 => 人 ADA 眼睛 女士 尼尼尼 基尼尼 ii 梅耶 初始化

                打印字符串中的所有回文:

                public class test1 {
                    public static void main(String[] args) {
                           String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
                           List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
                          System.out.println(list);
                          List<String> plist = new ArrayList<>();
                          for(int i = 0 ; i <list.size();i++) {
                              String curr =list.get(i);
                              if(ispalin(curr)) {plist.add(curr);}
                          }//for
                          System.out.println("palindrome list => " +plist);
                
                }//main
                
                    private static boolean ispalin(String curr) {
                        if(curr == null || curr.length() == 0) {return false;}
                        return new StringBuffer(curr).reverse().toString().equals(curr);
                    }
                
                }
                

                输出为:回文列表 => [MADAM, GiniiniG]

                Java 8 中的另一种方法:

                public class B {
                    public static void main(String[] args) {
                        String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
                        List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
                
                        // list to stream
                        // for Multi Threaded environment
                        Stream<String> stream = list.parallelStream();
                
                        // also,Stream<String> stream = list.stream(); for single Threaded environment
                        long palindrome = stream.filter(B::isPalindrome)// find all palindromes
                                .peek(System.out::println) // write each match
                                .count();// terminal - return a count
                        System.out.println("Count of palindromes: " + palindrome);
                        // System.out.println("List => " + list);
                
                
                    }
                
                    private static boolean isPalindrome(String aa) {
                
                        return new StringBuffer(aa).reverse().toString().equals(aa);
                
                    }
                }
                

                输出: 基尼尼 女士 回文数:2

                【讨论】:

                  【解决方案10】:

                  Java 程序通过连接每个单词的所有第一个字符来输入字符串并框定单词。

                  显示一个新词。

                  import java.util.*;
                  public class Anshu {
                   public static void main(String args[]) {
                    Scanner in = new Scanner(System.in)
                    System.out.println("Enter a string");
                    String s = in .nextLine();
                    char ch = s.charAt(0);
                    System.out.print(ch);
                    s = s.toUpperCase;
                    int l = s.length();
                    for (int i = 0; i < l; i++)
                     char a = s.charAt(i);
                    if (Character.isWhiteSpace())
                     System.out.print(s.charAt(i + 1) + "");
                   }
                  }
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2013-07-01
                    • 2012-10-12
                    相关资源
                    最近更新 更多