5 回答
TA贡献1848条经验 获得超6个赞
您可以使用字符位置来确定它是否存在于字符串中的其他位置。考虑以下解决方案:
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贡献1844条经验 获得超8个赞
要解决这类问题,这个解决方案可以很容易地解决你的问题,但这里我们只是采用一个256长度数组的常量空间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.."); }
我希望你有个主意..
TA贡献1799条经验 获得超8个赞
就个人而言,我不会使用数组来做到这一点 - 我会使用地图。即使你必须使用数组,我仍然会以地图的精神解决这个问题。
这里的counter
数组就像一个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贡献1852条经验 获得超7个赞
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
添加回答
举报