字符

520. 检测大写字母

image.png

题解

  1. class Solution {
  2. public boolean detectCapitalUse(String word) {
  3. char[] ch=word.toCharArray();
  4. int min=-1,max=-1;
  5. for(int i=0;i<ch.length;i++){
  6. if(ch[i]>='a'&&ch[i]<='z'){
  7. min=i;
  8. }else{
  9. max=i;
  10. }
  11. }
  12. if(max==0&&min==ch.length-1){
  13. return true;
  14. }else if(max==ch.length-1&&min==-1){
  15. return true;
  16. }else if(max==-1&&min==ch.length-1){
  17. return true;
  18. }else{
  19. return false;
  20. }
  21. }
  22. }

这是题解,用记录大小写字母的下标的变量,来判断所有满足条件的情况,不满足的全部返回false。

回文字符串

125. 验证回文串

image.png

题解一

  1. class Solution {
  2. public boolean isPalindrome(String s) {
  3. char[] ch=s.toLowerCase().toCharArray();
  4. for(int i=0,j=ch.length-1;i<=j;){
  5. while((ch[i]<'a'||ch[i]>'z')&&i<j){
  6. if(ch[i]>='0'&&ch[i]<='9'){
  7. break;
  8. }
  9. i++;
  10. }
  11. while((ch[j]<'a'||ch[j]>'z')&&i<j){
  12. if(ch[j]>='0'&&ch[j]<='9'){
  13. break;
  14. }
  15. j--;
  16. }
  17. if(i>=j){
  18. return true;
  19. }
  20. if((ch[j]==ch[i])&&i<j){
  21. i++;
  22. j--;
  23. }else{
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. }

将字符串大写变小写,每次去取是字母或者数字的下标,比较,如果刚好不等于,直接返回false,如果两边都遍历完,那么证明改字符是一个回文字符串。
注:回文字符串可以用中心拓展法来进行比较,当时这个回文字符串不能有其他不必要字符,不然需要处理字符串之后才能取到中心位置。

题解二