Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama"
is a palindrome."race a car"
is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
Answer:public boolean isPalindrome(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
char a = s.charAt(i);
char b = s.charAt(j);
while (i < j && !Character.isLetter(a) && !Character.isDigit(a)) {
a = s.charAt(++i);
}
while (j > i && !Character.isLetter(b) && !Character.isDigit(b)) {
b = s.charAt(--j);
}
if (Character.toLowerCase(a) != Character.toLowerCase(b)) {
return false;
}
}
return true;
}
Answer 2:
/*
public class EventBus {
HashMap<String, List<Event>>
public void register(String eventName, Event event) {};
public void unregister(String eventName, Event event){};
public void postEvent(String eventName, Object Data){};
public interface Event {
void onEvent(Object data);
}
}
*/
class EventBus {
private Map<String, List<Event>> map;
public EventListener() {
map = new HashMap<String, List<Event>>();
}
public void register(String eventName, Event event) {
if (map.containsKey(eventName)) {
map.get(eventName).add(event);
} else {
List<Event> events = new ArrayList<Event>();
events.add(event);
map.put(eventName, events);
}
};
public void unregister(String eventName, Event event) {
if (map.containsKey(eventName)) {
map.get(eventName).remove(event);
}
};
public void postEvent(String eventName, Object data) {
if(map.containsKey(eventName)){
List<Event> events = map.get(eventName);
for(Event event : events){
event.doEvent(data);
}
}
/*Event event = new Event();
event.doEvent(data);
this.register(eventName, event);
*/
};
}
class Event {
private Object data;
public void doEvent(Object data) {
this.data = data;
};
}
No comments:
Post a Comment