繁体   English   中英

在字符串中查找重复的字符

[英]Look for repeated characters in a string

我知道这个问题被问了很多次,但我没有发现任何对我的情况有帮助的答案。 我有一个接收字符串的方法。 我想检查字符串中的任何字符是否重复。 如果是这样,该方法将返回一个空字符串。 如果不是,它将返回字符串。 该方法正在寻找字符串中的任何重复字符。

private String visit(String word) {
    int count = 0;
    if(word == ""){
        return "<empty>";
    }
    //alphabet is an array that holds all characters that could be used in the String
    for(int i = 0; i < alphabet.length; i++){  
        for(int j = 0; j < word.length(); j++){

            if(alphabet[i] == word.charAt(j)){
                count++;
            }
            if(count == 2){                 
                return "";                                              
            }
        }
        count = 0;
    }           
    return word;        
}

好的,我发布了我的解决方案:

package main;

import java.util.Arrays;

public class main {

    public static void main(String[] args) {
        System.out.println(hasDups("abc"));
        System.out.println(hasDups("abcb"));
    }

    public static String hasDups(String arg) {
        String[] ar = arg.split("");
        Arrays.sort(ar);
        boolean noDups = true;
        for (int i = 1; i < ar.length && noDups; i++) {
            if (ar[i].equals(ar[i-1])) noDups = false;
        }

        if (noDups) return arg; else return "";
    }
}

这可能不是您想要的最佳方式,但是您可以使用两个for循环来检查每个字符与所有其他字符是否重复。

public static String hasRepeated(String word) {
    if (word.isEmpty()) return "<empty>";
    char[] charArray = word.toCharArray();
    for (int i = 0; i < charArray.length; i++) {
        for (int j = 0; j < charArray.length; j++) {
            if (i == j) {
            } else if (Character.toString(charArray[i]).
                    equalsIgnoreCase(Character.toString(charArray[j]))) {
                return "";
            }
        }
    }
    return word;
}

注意:此代码假设字符的大小写无关紧要,它只是检查是否重复。

   /**
    * Returns the index of the first character repeated, or -1 if no repeats
    */
   public static int firstRepeated( String s ) {
      if ( s != null ) {
         int n = s.length();
         for (int i = 0; i < (n - 1); i++) {
            int indx = s.indexOf( s.charAt( i ), i + 1 );
            if ( indx > 0 ) {
               return i;
            }
         }
      }
      return -1;
   }

这有效!!

public static String checkDuplicate(String str)
{
    int count = 0;

    char[] charArray = str.toCharArray();
    for(int i=0;i<charArray.length;i++)
    {
        count = 0;
        for(int j=0;j<charArray.length;j++)
        {
            if(charArray[i]==charArray[j])
            {

                count++;
                if(count==2) break;
            }
        }
        if(count==2) break;
    }
    if(count==2)
        return "";
    else
        return str;
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM