如何返回一个整数,表示回文的不同子字符串的数量?

时间:2017-09-25 22:16:29

标签: java

任何人都可以帮我处理我的代码吗?因为我不明白我做错了什么。谢谢!

以下是我的代码:

public class Solution{

//code I need Help with:

public static int palindromeCount(String s) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        for (int j = 0; j < s.length(); j++) {
            if (s.charAt(i) == s.charAt(j)) {
            }
            count++;
        }
        break;
    }

    return count;
}

//Given and can't change:

public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    final String fileName = System.getenv("OUTPUT_PATH");
    BufferedWriter bw = null;
    if (fileName != null) {
        bw = new BufferedWriter(new FileWriter(fileName));
    } else {
        bw = new BufferedWriter(new OutputStreamWriter(System.out));
    }

    int res;
    String s;
    try {
        s = in.nextLine();
    } catch (Exception e) {
        s = null;
    }

    res = palindromeCount(s);
    bw.write(String.valueOf(res));
    bw.newLine();

    bw.close();
    }
  }

输出: 你的函数必须返回一个整数,表示s的不同子字符串的数量是回文。

Ex输入:

s = aabaa

输出:

5

原因:a,aa,aabaa,aba,b

子字符串'a'出现4次,但我们正在寻找不同的子字符串。然后只计算一次。同样,字符串'aa'出现两次但计为一个不同的回文。

2 个答案:

答案 0 :(得分:0)

您可以将每个字符串添加到集合中(不能包含重复项),而不是使用int计数,而函数末尾只返回Set的大小。

https://docs.oracle.com/javase/7/docs/api/java/util/Set.html

答案 1 :(得分:0)

以下是如何使用Set消除重复项的实现。

import java.util.*; //Needed import to use the Set

  public static void main(String[] args)
  {
    String s = "aabaa";  //Test String - Has 5 palindroms: a, aa, aabaa, aba, b 
    HashSet<String> countSet = new HashSet<String>();  //Use a Set since it will elimate duplicate values
    for (int i = 0; i < s.length(); i++) { 
        for (int j = i+1; j <= s.length(); j++) {  //check every substring possibility
            if(isPalindrom( s.substring(i,j).toCharArray() ) ) //If the substring is a palindrom...
            {
              countSet.add(s.substring(i,j)); //... add it to our Set.  Duplicates will be ignored because it is a Set
            }
        }
    }

    System.out.println("HERE: " + countSet.size());  //The number of palindroms.  5 in this case
  }

  //Fuction that checks if a char[] is a palindrom
  public static boolean isPalindrom(char[] word){
    int i1 = 0;
    int i2 = word.length - 1;
    while (i2 > i1) {
        if (word[i1] != word[i2]) {
            return false;
        }
        ++i1;
        --i2;
    }
    return true;
  }