5 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用字符位置來確定它是否存在于字符串中的其他位置。考慮以下解決方案:
while (df.hasNextLine()) { String line = df.nextLine(); String array[] = line.split(""); String ans = "USES DISTINCT LETTERS"; for (int k = 0; k < array.length; k++) { if(line.indexOf(array[k]) != line.lastIndexOf(array[k])){ ans = "DOES NOT USE DISTINCT LETTERS"; break; } }//FOR LOOP System.out.println(line + " " + ans); }//WHILE DF

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
要解決這類問題,這個(gè)解決方案可以很容易地解決你的問題,但這里我們只是采用一個(gè)256長度數(shù)組的常量空間complexity will be O(n)
:
int []star = new int[256]; while (df.hasNextLine()) { Arrays.fill(star,0); String line = df.nextLine(); for(int i=0;i<line.length();i++){ star[line.charAt(0)]++; } for(int i=0;i<256;i++){ if(star[i]>0 && star[i]>1){ System.out.println("Duplicate characters present.."); } } System.out.println("No Duplicate characters present.."); }
我希望你有個(gè)主意..

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
就個(gè)人而言,我不會(huì)使用數(shù)組來做到這一點(diǎn) - 我會(huì)使用地圖。即使你必須使用數(shù)組,我仍然會(huì)以地圖的精神解決這個(gè)問題。
這里的counter
數(shù)組就像一個(gè)map(key = index,value = count)。
public class Test { public static void main(String[] args) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get("data/input.csv")); String s = new String(encoded, Charset.defaultCharset()); String[] split = s.split("\n"); System.out.println("Input: " + Arrays.toString(split)); System.out.println("Output: " + Arrays.toString(check(split))); } private static String[] check(String[] strings) { for (int i = 0; i < strings.length; i++) strings[i] += distinct(strings[i]) ? " USES DISTINCT LETTERS" : " DOES NOT USE DISTINCT LETTERS"; return strings; } private static boolean distinct(String string) { int[] counter = new int[string.length()]; for (char c : string.toCharArray()) if (++counter[string.indexOf(c)] > 1) return false; return true; }}
Input: [UNCOPYRIGHTABLE, FLIPPER, EXECUTABLE, UNPROFITABLE, QUESTIONABLE, WINDOW, TAMBOURINE]
Output: [UNCOPYRIGHTABLE USES DISTINCT LETTERS, FLIPPER DOES NOT USE DISTINCT LETTERS, EXECUTABLE DOES NOT USE DISTINCT LETTERS, UNPROFITABLE USES DISTINCT LETTERS, QUESTIONABLE DOES NOT USE DISTINCT LETTERS, WINDOW DOES NOT USE DISTINCT LETTERS, TAMBOURINE USES DISTINCT LETTERS]

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
for (int k = 0; k < array.length; k++)
{
for (int m = k + 1; m < array.length; m++)
{
if (!array[k].equals(array[m])
{
ans = "USES DISTINCT LETTERS";
}
else
{
ans = "DOES NOT USE DISTINCT LETTERS";
// Break out of the two loops once you know the characters are matching.
//Otherwise it loops again and the last match of character is what you get the ans.
}
}//FOR LOOP2
}//FOR LOOP
添加回答
舉報(bào)