This is an interview question.
For the purpose of the question, a valid English word is a string that begins with an uppercase English letter, and the rest of the string contains only lowercase English letters. I needed to implement two functions:
- A function that receives a String and returns true if the String is a valid English word, and false otherwise.
A function that receives a String and convert it to a valid english word. That means that the function removes non-English characters from the string, and also lowercase\uppercase letters that are in the wrong place. Examples:
convertToValidString("A") = "A" convertToValidString("a") = "" convertToValidString("Ab") = "Ab" convertToValidString("AB") = "A" convertToValidString("Ab5eA") = "Abe" convertToValidString("aAd") = "Ad" convertToValidString("a6d") = ""
Below is the code I wrote, please tell me what do you think. My emphasis is mainly about efficiency (run time + short code), and less about coding conventions.
public static boolean isValidString(String s){
int len = s.length();
if (len == 0) return true;
if ( (s.charAt(0) < 65) || (s.charAt(0) > 90) ) return false;
for (int i = 1; i < len; i++){
if ( (s.charAt(i) < 97) || (s.charAt(i) > 120) ) return false;
}
return true;
}
public static String convertToValidString(String s) {
StringBuffer ans = new StringBuffer();
int len = s.length();
int i = 0;
while ( (i < len) && ((s.charAt(i) < 65) || (s.charAt(i) > 90)) )
i++;
if (i < len){
ans.append(s.charAt(i));
i++;
for (; i < len; i++){
if ( (s.charAt(i) >= 97) && (s.charAt(i) <= 120) )
ans.append(s.charAt(i));
}
}
return ans.toString();
}