2015-05-15 36 views
-1

我正在嘗試查找字符串的所有可能的不同子字符串。這是我當前的代碼:給定字符串的不同子字符串

import java.util.Scanner; 

public class Solution { 

    public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 
     String str = sc.nextLine(); 

     StringBuffer f = new StringBuffer(); 

     //Get a string of possible substrings with out uniqueness 
     for (int i = 0; i < str.length(); i++) { 
      for (int j = i; j < str.length(); j++) { 
       f.append(str.charAt(j) + ","); 
      } 
     } 

     f.deleteCharAt(sb.length() - 1); 
     String s = f.toString(); 
     String[] arr = s.Split(','); 
     arr = arr.Distinct().ToArray(); 

     for (int i = 0; i < arr.length; i++) 
      System.out.println(arr[i]); 
    } 
} 

編譯時收到多個錯誤。我不明白代碼出錯的地方。我忘了導入課程還是有語法錯誤?

Solution.java:28: error: cannot find symbol 
f.deleteCharAt(sb.length()-1); 
      ^
symbol: variable sb 
location: class Solution 
Solution.java:31: error: cannot find symbol 
String[] arr = s.Split(','); 
       ^
symbol: method Split(char) 
location: variable s of type String 
Solution.java:34: error: cannot find symbol 
arr = arr.Distinct().ToArray(); 
     ^
symbol: method Distinct() 
location: variable arr of type String[] 
3 errors 
+7

'final'是Java中的保留字。嘗試調用其他變量。 – legoscia

+4

另外Java是區分大小寫的,所以'Length'!='length'。另一件事是'String'沒有'length'字段,但是它有'length()'方法。 – Pshemo

+2

我會補充說,Split()是split()(大寫) – Tavo

回答

1

這是很難理解你打算做什麼,但是當你說一個給定的字符串的不同子我不認爲你的意思是獨特的字母。所以看看這個...

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    String str = sc.nextLine(); 

    for (int i = 0; i < str.length(); i++) { 
     for (int j = i + 1; j < str.length() + 1; j++) { 
      String substring = str.substring(i, j); 

      if (str.indexOf(substring, i + substring.length()) == -1) { 
       System.out.println("Unique Substring: " + substring); 
      } 
     } 
    } 
} 

我測試了這個與「你好」,給你的評論最後的答案。您會注意到由於下一個「l」(小寫字母L),第一個「l」(小寫字母L)不是結果的一部分,但第二個「l」(小寫字母L)是唯一子字符串。

enter image description here

這是你在找什麼?

+0

是的,謝謝你,我正在等待這段代碼! – coder101

+0

@ coder101不客氣...請檢查我的答案,以便您的問題得到解決。 – Shar1er80

0

以下是獲取唯一或不同值的有效方法。 HashSet不允許重複,因此您可以先準備一個具有重複值的ArrayList,並將其傳遞給HashSet的構造函數,並將所有重複項移除。

String[] str = {"A", "B", "A", "C", "D", "B"}; 
List<String> arrayList = Arrays.asList(str);; 
System.out.println(arrayList); 
HashSet<String> hashSet = new HashSet<String>(arrayList); 
System.out.println(hashSet); 
+0

用於輸入hello它給出了 [h,e,l,l,o,] [h,e,l,l,o ,]作爲輸出! – coder101

+0

你能分享你的代碼嗎? – hagrawal

相關問題