java - detect duplicate character in string -


i doing exercises in cracking coding interview book , trying determine if there duplicate character in string. using arraylist data structure. method of return type boolean, returns true if there duplicate , returns false if there no duplicate character. added third return statement program compile returns false.

import java.util.*;  public class questiononecrackingcode {      public static void main(string[] args) {         string s = "abcdefga";         arraylist<string> c = new arraylist<string>();         c.add(s);          system.out.print(check(c));     }      public static boolean check(arraylist<string> g) {         (int = 0; < g.size(); i++) {             (int j = + 1; j < g.size(); j++) {                 if (g.get(i) == g.get(j)) {                     return true;                 } else {                     return false;                 }             }         }         return false;     } } 

you're not separating string characters, you're creating single-element list containing string. without making big changes algorithm, this:

public static void main(string[] args) {     string s = "abcdefga";      system.out.print(check(s)); }  public static boolean check(charsequence g) {     (int = 0; < g.length(); i++) {         (int j = + 1; j < g.length(); j++) {             if (g.charat(i) == g.charat(j)) {                 return true;             }         }     }     return false; } 

note first return false; incorrect because stop algorithm continuing past first comparison.

as aside, when are comparing strings, should use .equals() instead of ==.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -